How httpclient sets timeout

Today, I share a huge pit, httpclient. How deep is this thing? Every version changes. Recently, the author has suffered a lot. First look at the code. I want to send a request to call a C + + interface.

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;
}

Well, the pit father's place is here. This thing sends requests without setting a timeout. As long as it doesn't respond, he can wait here all the time. Who can stand it. I want to add a timeout. The second pit is coming. I remember setting the timeout like this before.

client.setConnectionTimeout(10000); 
client.setTimeout(10000);

I found that there is no such method. So I looked up the information. Found httpclient too fickle. Each version becomes an API. Version 4.3 is like this

httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,10000);
httpClient.getParams().setParameter(CoreConnectionPNames.so_TIMEOUT,10000);

This will be the case after 4.3.

RequestConfig requestConfig =  RequestConfig.custom().setSocketTimeout(10000).setConnectTimeout(10000).build();
httpGet.setConfig(requestConfig);

Finally, according to my version, I chose the way of 4.3 to solve the problem.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>