HttpClient 4.5.2 version sets connection timeout - CloseableHttpClient sets Timeout

HttpClient 4.5 version sets the connection timeout - CloseableHttpClient sets Timeout (different from 4.3.2)

 

After HttpClient is upgraded to version 4.5, there are many changes to the API. After HttpClient 4, the API has not been too stable. I feel that after the 4.5 version is abstracted, many APIs should be stable.

With HttpClient, you usually need to set the connection timeout and get the data timeout. These two parameters are important in order to prevent your application from being affected due to timeouts when accessing other https.

In version 4.5, the settings of these two parameters are abstracted into RequestConfig and built by the corresponding Builder. The specific examples are as follows:

CloseableHttpClient httpclient = HttpClients.createDefault();  
HttpGet httpGet = new HttpGet("http://stackoverflow.com/");  
RequestConfig requestConfig = RequestConfig.custom()  
        .setConnectTimeout(5000).setConnectionRequestTimeout(1000)  
        .setSocketTimeout(5000).build();  
httpGet.setConfig(requestConfig);  
CloseableHttpResponse response = httpclient.execute(httpGet);  
System.out.println("Get the result:" + response.getStatusLine());//Get the requested result
 HttpEntity entity = response.getEntity();//Get the data back from the request

setConnectTimeout: Sets the connection timeout in milliseconds.

setConnectionRequestTimeout: Sets the connection timeout time in milliseconds from the connect manager. This property is a new property because the current version is a shared pool.

setSocketTimeout: Timeout in milliseconds for requesting data. If you access an interface and can't return data for a while, just abandon the call.

===========================================

Yesterday encountered a problem need to set the timeout time of CloseableHttpClient, check the official documents are as follows.

Create a new RequestConfig:

RequestConfig defaultRequestConfig = RequestConfig.custom()
    .setSocketTimeout(5000)
    .setConnectTimeout(5000)
    .setConnectionRequestTimeout(5000)
    .setStaleConnectionCheckEnabled(true)
    .build();

This timeout can be set to the client level as the default for all requests:

CloseableHttpClient httpclient = HttpClients.custom()
    .setDefaultRequestConfig(defaultRequestConfig)
    .build();

Request does not inherit the client-level request configuration, so when customizing the Request, you need to copy the client's default configuration:

 
HttpGet httpget = new HttpGet("http://www.apache.org/");
RequestConfig requestConfig = RequestConfig.copy(defaultRequestConfig)
    .setProxy(new HttpHost("myotherproxy", 8080))
    .build();
httpget.setConfig(requestConfig);

 

The timeout for version 4.3 is like this:

public static String httpPost(String url, String jsonString) {
    / / Set the HTTP request parameters
String result = null;
    HttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(url);
    try {
        httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000);/ / Set the request timeout time 10s
StringEntity entity = new StringEntity(jsonString);
        entity.setContentEncoding("UTF-8");
        entity.setContentType("application/json");
        httpPost.setEntity(entity);
        HttpEntity resEntity = httpClient.execute(httpPost).getEntity();
        result = EntityUtils.toString(resEntity, "UTF-8");
    } catch (Exception e) {
        logger.error("http interface call exception: url is::" + url, e);
        return null;
    } finally {
        httpClient.getConnectionManager().shutdown();
    }
    return result;
}

 

The 4.5.2 version is like this:

 public static String testTimeout(String url) {

/ / Set the HTTP request parameters

        String result = null;

        CloseableHttpClient client = HttpClients.createDefault();

        HttpGet httpGet = new HttpGet(url);

        RequestConfig requestConfig = RequestConfig.custom()

                .setConnectTimeout(50000).setConnectionRequestTimeout(10000)

                .setSocketTimeout(50000).build();

        httpGet.setConfig(requestConfig);

        try {

            CloseableHttpResponse response = client.execute(httpGet);

            result = EntityUtils.toString(response.getEntity(), "UTF-8");

        } catch (ClientProtocolException e) {

Logger.error("http interface call exception: url is::" + url, e);

            return null;

        } catch (Exception e) {

Logger.error("http interface call exception: url is::" + url, e);

            return null;

        } finally {

            try {

                client.close();

            } catch (IOException e) {

Logger.error("http interface call exception: url is::" + url, e);

            }

        }

        return result;

    }

 

 

Intelligent Recommendation

Apache HttpClient sets the request timeout time and return timeout time, and timeout retry

There is no timeout setting for socket read, which will cause HttpClient to block.Because the default SO_TIMEOUT of Http Client is 0, that is, it has been waiting. Apache HttpClient needs to set TimeO...

HttpURLConnection sets the network timeout

Java can use HttpURLConnection to request WEB resources. The HttpURLConnection object cannot be constructed directly. The HttpURLConnection object needs to be obtained through URL.openConnection(). Th...

How JDBC sets the timeout

Proper JDBC timeout settings can effectively reduce the time to service failure. This article will introduce the various timeout settings of the database and its setting methods. Real case: Applicatio...

Jedis sets the timeout for the key

Only one text message can be sent in one minute. If the user refreshes the page and then enters the original phone number, continue counting Program:The server side should record the timestamp Method ...

Fetch sets the network timeout

The key method promise.race([]); When a method inside triggers resolve or reject, the resolve and reject of other promises will not be triggered....

More Recommendation

Fetch function sets timeout

When using the react-native development app, you usually use the fetch function to interact with the background. When requesting the background interface, in order to prevent the user from waiting too...

Gin sets Timeout

Original address:https://gist.github.com/montanaflynn/ef9e7b9cd21b355cfe8332b4f20163c1(need to overturn the wall)...

Applet sets request timeout

Configure in app.json...

shiro sets the session timeout

The system default timeout period is 180000 milliseconds (30 minutes) You can set a custom timeout time in the following 2 ways One: Configuration file Two: through api Shiro's Session interface has a...

Copyright  DMCA © 2018-2026 - All Rights Reserved - www.programmersought.com  User Notice

Top