httpclient timeout and proxy settings

overtime time

Set HttpClient timeout, very necessity, because httpclient default timeout very long, they can test how long to set the timeout otherwise it will affect the business logic of their own systems, such as blocking throughput of the system, affecting the system, taking up the thread number.

After these settings httpclient 4.4 version RequestConfig encapsulated in objects, wherein setConnectTimeout is provided connected to the length of time, the destination URL, the time has not exceeded the timeout even throw connected;

setConnectionRequestTimeout from connect Manager (the connection pool) obtaining long wait for a connection, this version is connected to the shared pool;

setSocketTimeout is a long waiting to return a response after connecting to the target URL, or more than the time to give up this call and throw SocketTimeoutException: Read Time Out

public static RequestConfig getRequestConfig(){
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(10000)
                .setSocketTimeout(10000)
                .setConnectionRequestTimeout(6000)
                .build();
        return requestConfig;
    }

 

Proxy settings

Sometimes when we line access to external third-party interface, you do not want to expose the real IP of the machine, or when our machines can not access the Internet, we can access through a proxy server, proxy server acts as an internal network and external network links middleman. After setting agent httpclient 4.4 IP, is encapsulated into RequestConfig target port, through HttpHost proxy object encapsulates IP, port, and protocol. One thing to note here is that if your goal URL is the HTTP protocol, then your agent should also be HTTP protocol, as the constructor HttpHost can specify the proxy service agreement does not pass the default is HTTP

public static RequestConfig getRequestConfig(){
        HttpHost proxy = new HttpHost("代理ip",443,"HTTP");//代理
        RequestConfig requestConfig = RequestConfig.custom()
                .setProxy(proxy)
                .setConnectTimeout(10000)
                .setSocketTimeout(10000)
                .setConnectionRequestTimeout(6000)
                .build();
        return requestConfig;
    }

 

Then setConfig HttpPost or HttpGet () method of its application to the config 

HttpPost httpPost = new HttpPost(url);
if(null != requestConfig){
    httpPost.setConfig(requestConfig);
}

 

Guess you like

Origin www.cnblogs.com/ibigboy/p/11245990.html