1. 程式人生 > >httpclient 工具 版本更新 doget 解決 輸出 返回 字串變少 問題

httpclient 工具 版本更新 doget 解決 輸出 返回 字串變少 問題

public static String doGet(String url) throws Exception {
logger.info("doGet - url:" + url);
String respJson = ""; // 響應內容
CloseableHttpClient httpClient = HttpClients.createDefault();


HttpGet httpGet = new HttpGet(url);
httpGet.addHeader("Content-Type", "application/json");
httpGet.addHeader("charset", "UTF-8");
RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(60000).setSocketTimeout(60000)
.setConnectTimeout(60000).build();// 設定請求和傳輸超時時間
httpGet.setConfig(requestConfig);


CloseableHttpResponse response = null;
try {
response = httpClient.execute(httpGet);
if (response.getStatusLine().getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
//respJson = EntityUtils.toString(entity);
if (entity != null) {
InputStream inputStream= entity.getContent();
respJson = IOUtils.toString(inputStream, "UTF-8");
}
}
} catch (Exception e) {
throw e;
} finally {
try {
if (response != null) {
response.close();
}
if (httpClient != null) {
httpClient.close();
}
} catch (IOException e) {
throw e;
}
}


logger.info("doGet - respJson:" + respJson);
return respJson;
}