java調用RestFul WebService的例子


pom文件

<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.3</version>
</dependency>


public void sendDataToRemote(){
Map<String,Double> map = new HashMap<String, Double>();
synchronized (PointValueService.mapLock){
map = PointValueService.map;
}
Gson gson = new Gson();
String url = ipAddress + "/receiveService/receiveRemoteService"; //訪問遠程方法路徑
String dataString = gson.toJson(map);
System.out.println("----------------dataString----------" + dataString);
try {
String data = CodecTools.compressAndEncode(dataString); // 壓縮后的實時數據信息
// TODO Java調用指定ip路徑下方法 accessPath
String t=CodecTools.decodeAndUncompress(data);
// System.out.println("data---------------"+data);
// System.out.println("t---------------"+t);
List<NameValuePair> params = new ArrayList<NameValuePair>();
// params.add(new BasicNameValuePair("userName", "Sun"));
params.add(new BasicNameValuePair("param",data));
getRest(url, params);
} catch (IOException e) {
e.printStackTrace();
}
}


public static String getRest(String url,List<NameValuePair> params){
// 創建默認的httpClient實例.
CloseableHttpClient httpclient = HttpClients.createDefault();
// 創建httppost
HttpPost httppost = new HttpPost(url);

UrlEncodedFormEntity uefEntity;

try{
uefEntity = new UrlEncodedFormEntity(params, "UTF-8");
httppost.setEntity(uefEntity);
CloseableHttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
String json= EntityUtils.toString(entity, "UTF-8");
int code= response.getStatusLine().getStatusCode();
if(code==200 ||code ==204){
return json;
}
}catch (Exception e){
e.printStackTrace();
}

return "";
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM