-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathrestful client for java
63 lines (55 loc) · 2.55 KB
/
restful client for java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class WeiboRestClient {
public final static String METHOD_GET="GET";
public final static String METHOD_PUT="PUT";
public final static String METHOD_DELETE="DELETE";
public final static String METHOD_POST="POST";
public static void rest(String serviceUrl,String parameter,String restMethod){
try {
URL url= new URL(serviceUrl);
HttpURLConnection con = (HttpURLConnection)url.openConnection();
con.setRequestMethod(restMethod);
//如果请求方法为PUT,POST和DELETE设置DoOutput为真
if(!WeiboRestClient.METHOD_GET.equals(restMethod)){
con.setDoOutput(true);
if(!WeiboRestClient.METHOD_DELETE.equals(restMethod)){ //请求方法为PUT或POST时执行
OutputStream os = con.getOutputStream();
os.write(parameter.getBytes("UTF-8"));
os.close();
}
}
else{ //请求方法为GET时执行
InputStream in= con.getInputStream();
byte[] b= new byte[1024];
int result= in.read(b);
while( result!=-1){
System.out.write(b,0,result);
result= in.read(b);
}
}
System.out.println(con.getResponseCode()+":"+con.getResponseMessage());
} catch ( Exception e ) {
throw new RuntimeException(e );
}
}
public static void main(String args[]){
// //GET
// rest("http://localhost:8081/sqlrest/PRODUCT/4",null,WeiboRestClient.METHOD_GET);
//
// //PUT
// String put="<?xml version=\"1.0\" encoding=\"UTF-8\" ?><PRODUCT xmlns:xlink=\"http://www.w3.org/1999/xlink\"><NAME>Chair Shoe</NAME>"
// +"<PRICE>24.8</PRICE></PRODUCT>";
// rest("http://localhost:8081/sqlrest/PRODUCT/395",put,WeiboRestClient.METHOD_PUT);
//
// //POST
// String post="<?xml version=\"1.0\" encoding=\"UTF-8\" ?><PRODUCT xmlns:xlink=\"http://www.w3.org/1999/xlink\">"
// +"<PRICE>98</PRICE></PRODUCT>";
// rest("http://localhost:8081/sqlrest/PRODUCT/395",post,WeiboRestClient.METHOD_POST);
//
// //DELETE
// rest("http://localhost:8081/sqlrest/PRODUCT/395",null,WeiboRestClient.METHOD_DELETE);
}
}