http-get調用接口簡單代碼

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

二、代碼以下:app

HttpGet get=null;url

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);
接口

//接口參數get

Map map = new HashMap<>();it

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();
}
}
}
}
 io

 三、根據接口返回數據判斷是否知足您的需求。class

相關文章
相關標籤/搜索