今天分享一個巨坑,就是 HttpClient。這玩意有多坑呢?就是每個版本都變,近日筆者深受其害。
先看一下代碼,我要發送請求調用一個c++接口。
public static String doPostWithJSON(String url, String json) throws Exception {
CloseableHttpClient client = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("Content-Type","application/json;charset=UTF-8");
StringEntity se = new StringEntity(json, Charset.forName("UTF-8"));
se.setContentType("application/json");
httpPost.setEntity(se);
CloseableHttpResponse response = client.execute(httpPost);
HttpEntity entity = response.getEntity();
String result = EntityUtils.toString(entity, "UTF-8");
return result;
}
嗯,坑爹的地方來了,這個玩意發送請求,沒設置超時時間,只要不響應,他能一直在這等着,這誰能受得了。
我要加個超時時間。
第二個大坑來了。
我記得以前設置超時時間是這樣的。
client.setConnectionTimeout(10000);
client.setTimeout(10000);
我發現,特么沒這個方法。
於是查閱資料。發現HttpClient太善變了。每個版本都變api。
4.3版本是這樣的
httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,10000);
httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,10000);
4.3以后是這樣的。
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(10000).setConnectTimeout(10000).build();
httpGet.setConfig(requestConfig);
最后我根據我的版本,選了4.3的那種方式,解決問題。