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

After HttpClient was upgraded to version 4.5, the API has changed a lot. After HttpClient 4, the API has not been too stable. I feel that after 4.5 version abstraction, many APIs should be stable soon.

       To use HttpClient, you generally need to set the connection timeout time and the data timeout time. These two parameters are very important. The purpose is to prevent your application from being affected due to timeout when accessing other http.

       In version 4.5, the settings of these two parameters are abstracted into RequestConfig and constructed by the corresponding Builder. 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("得到的结果:" + response.getStatusLine());//得到请求结果  
HttpEntity entity = response.getEntity();//得到请求回来的数据

setConnectTimeout: Set the connection timeout time, in milliseconds.

setConnectionRequestTimeout: Set the timeout period for obtaining Connection from connect Manager, in milliseconds. This attribute is a newly added attribute, because the current version can share the connection pool.

setSocketTimeout: The timeout period for requesting to obtain data, in milliseconds. If you access an interface and fail to return data for a certain amount of time, you will simply abandon the call.

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

I encountered a problem yesterday and needed to set the timeout period of CloseableHttpClient. I checked the official document as follows.

Create a new RequestConfig:

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

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

CloseableHttpClient httpclient = HttpClients.custom()
    .setDefaultRequestConfig(defaultRequestConfig)
    .build();
Request does not inherit the client-level request configuration, so when customizing 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) {
    // 设置HTTP请求参数
String result = null;
    HttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(url);
    try {
        httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000);//设置请求超时时间 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接口调用异常: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 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;

    }

Guess you like

Origin blog.csdn.net/zhaofuqiangmycomm/article/details/114526742