http-post調用接口簡單代碼


一、簡單便捷的httpget調用接口,並且返回接口數據
1、導入相應的jar包;

2、代碼如下:

HttpPost post = null;
try {
HttpClient httpClient = new DefaultHttpClient();
// 設置超時時間
httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 20000);
httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 20000);

post = new HttpPost(url);
// 構造消息頭
// post.setHeader("Content-type", contenttype);
post.setHeader("rxToken", rxToken);
post.setHeader("source", source);
Map map = new HashMap<>();
// map.put("bizType", "1");
// map.put("pageNo", 1);
// map.put("pageSize", 1000);
// map.put("orgId", 1);
// List list=new ArrayList<>();
// list.add(0);
// list.add(1);
// map.put("memberTypes", list);
// map.put("isLosts", list);
JSONObject json =new JSONObject(map);
// 構建消息實體
StringEntity entity = new StringEntity(json.toString(), Charset.forName("UTF-8"));
entity.setContentEncoding("UTF-8");
// 發送Json格式的數據請求
entity.setContentType("application/json");
post.setEntity(entity);
HttpResponse response = httpClient.execute(post);
// 檢驗返回碼
int statusCode = response.getStatusLine().getStatusCode();
if(statusCode != HttpStatus.SC_OK){
System.out.println("錯誤接口返回==="+statusCode);
HttpEntity entity1 = response.getEntity();//獲取響應實體
long aaa = entity1.getContentLength();//獲取相應數據大小
if (aaa == -1) {//如果為-1,則重置date_size
}
content = EntityUtils.toString(entity1);//解析響應
System.out.println("接口返回==="+content);
}else{
HttpEntity entity1 = response.getEntity();//獲取響應實體
long aaa = entity1.getContentLength();//獲取相應數據大小
if (aaa == -1) {//如果為-1,則重置date_size
}
content = EntityUtils.toString(entity1);//解析響應
System.out.println("接口返回==="+content);
}
} catch (Exception e) {
e.printStackTrace();
}finally{
if(post != null){
try {
post.releaseConnection();
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

 3、根據接口返回數據判斷是否滿足您的需求。


免責聲明!

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



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