HttpClient 如何設置超時時間


今天分享一個巨坑,就是 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的那種方式,解決問題。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM