http-get調用接口簡單代碼


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

2、代碼如下:

HttpGet get=null;

try {
HttpClient httpClient = new DefaultHttpClient();
// 設置超時時間
httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 20000);
httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 20000);
String url = "http://xxxx.xxx.xx.xx.com";
get = new HttpGet(url);
// 構造消息頭
get.setHeader("Content-type", contenttype);
get.setHeader("Authorization", authorization);

//接口參數

Map map = new HashMap<>();

map.put("fileName",file);
JSONObject json =new JSONObject(map);
// 構建消息實體
// StringEntity entity = new StringEntity(json.toString(), Charset.forName("UTF-8"));
// entity.setContentEncoding("UTF-8");
// 發送Json格式的數據請求
// entity.setContentType("application/json");

// get.setEntity(entity);
HttpResponse response = httpClient.execute(get);
// 檢驗返回碼
int statusCode = response.getStatusLine().getStatusCode();
if(statusCode != HttpStatus.SC_OK){
System.out.println("錯誤接口返回==="+statusCode);

}else{
HttpEntity entity1 = response.getEntity();//獲取響應實體
BufferedHttpEntity bufferedHttpEntity = new BufferedHttpEntity(entity1);
InputStream is = bufferedHttpEntity.getContent();
return is;
// 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(get != null){
try {
get.releaseConnection();
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
 

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


免責聲明!

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



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