current position:Home>Httpclient setting timeout

Httpclient setting timeout

2022-04-29 06:38:34Chen, hard work

Recently, when the program calls back the request , encounter httpClient Request exception , Sometimes you can , Sometimes abnormal . Add timeout and failure reconnection mechanism to handle . Make a note of .

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 The request configuration at the client level will not be inherited , So in customizing Request When , You need to copy the default configuration of the client :

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

encapsulation sendPost request :

	/** *  Assign to  URL  send out POST Method request  * * @param url  Send requested  URL * @param params  Request parameters  * @param charset  Character set  * @param headers  Header information  * @return  Response result of the remote resource represented  */
    public static String sendPost(String url, Map<String, Object> params, String charset, Map<String, String> headers) {
    
        StringBuffer resultBuffer;
        HttpClient client;
        BufferedReader br = null;
        try {
    
            if (url.startsWith("https://")) {
    
                client = new SslClient();
            } else {
    
                client = new DefaultHttpClient();
            }

            HttpPost httpPost = new HttpPost(url);
            //  Set timeout 
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(5000).setConnectionRequestTimeout(1000)
                    .setSocketTimeout(5000).build();
            httpPost.setConfig(requestConfig);
            //  Build request parameters 
            List<NameValuePair> list = new ArrayList<>();
            Iterator<Map.Entry<String, Object>> iterator = params.entrySet().iterator();
            while (iterator.hasNext()) {
    
                Map.Entry<String, Object> elem = iterator.next();
                if (elem.getValue() != null) {
    
                    list.add(new BasicNameValuePair(elem.getKey(), String.valueOf(elem.getValue())));
                }
            }

            if (list.size() > 0) {
    
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, charset);
                httpPost.setEntity(entity);
            }

            if (headers != null) {
    
                for (Map.Entry<String, String> entry : headers.entrySet()) {
    
                    httpPost.addHeader(entry.getKey(), entry.getValue());
                }
            }

            HttpResponse response = client.execute(httpPost);
            //  Read server response data 
            resultBuffer = new StringBuffer();
            br = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), charset));
            String temp;
            while ((temp = br.readLine()) != null) {
    
                resultBuffer.append(temp);
            }
        } catch (Exception e) {
    
            throw new RuntimeException(e);
        } finally {
    
            if (br != null) {
    
                try {
    
                    br.close();
                } catch (IOException e) {
    
                    br = null;
                    throw new RuntimeException(e);
                }
            }
        }
        return resultBuffer.toString();
    }

setConnectTimeout: Set connection timeout , Unit millisecond .

setConnectionRequestTimeout: Set from connect Manager obtain Connection Timeout time , Unit millisecond . This attribute is a new attribute , Because the current version can share the connection pool .

setSocketTimeout: Timeout for request to get data , Unit millisecond . If you access an interface , How much time can't return data , Just give up the call .

Reference material :

http://blog.csdn.net/zheng0518/article/details/46469051
https://segmentfault.com/a/1190000000587944
http://my.oschina.net/wallechen/blog/526642

copyright notice
author[Chen, hard work],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2022/04/202204290638297311.html

Random recommended