java後臺HTTP請求其他專案介面
阿新 • • 發佈:2018-12-26
需要引用的包
org.apache.httpcomponents httpclient 4.3.5建立一個工具類對專案以外的介面驚喜HTTP請求,該介面返回的是一個String的字串,這個字串就是你需要的資料,在需要的地方呼叫該介面
static public String get(String url) throws IOException{
//建立一個預設連線
String result=null;
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(url);
CloseableHttpResponse response = httpClient.execute(httpGet);
//獲取狀態嗎,判斷狀態
int statusCode = response.getStatusLine().getStatusCode();
if(statusCode==200){
org.apache.http.HttpEntity entity = response.getEntity();
result = EntityUtils.toString(entity,“UTF-8”);
System.out.println(“result:”+result);
}
return result;
}