HttpClient 如何設定超時時間
阿新 • • 發佈:2020-12-30
今天分享一個巨坑,就是 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的那種方式,解決問題。