CloseableHttpClient set timeout

There are many Java developers we often need to communicate, communicate, and the way third-party systems, such as dubbo way, webservice, micro services and CloseableHttpClient, etc., often involving a time-out issue, where the main talking timeout setting CloseableHttpClient and supermarket exception handling; the general idea is,

1, defined timeout, this is generally as a configuration item, easy to modify;

2, the object request configuration settings RequestConfig timeout, and then provided to the requesting HttpPost HttpGet or method of the object;

3, to perform the requested method CloseableHttpClient objects while using try ... catch ... catch the exception, and for the timeout by SocketTimeoutExcetption ConnectTimeoutException catch exceptions;

For example, the following brief example (corresponding to the Internet to find their own jar);

package com.xxx.yyy.kkk;

import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.BasicHttpClientConnectionManager;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;

import java.io.IOException;
import java.net.SocketTimeoutException;

public class HttpClient001 {

public void getXXX() throws Exception {
CloseableHttpClient httpclient = HttpClients.createDefault();
RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(1000)
.setSocketTimeout(1000).setConnectTimeout(1000).build();
HttpGet httpGet = new HttpGet("http://www.xxx.com");
httpGet.setConfig(requestConfig);
try {
CloseableHttpResponse response = httpclient.execute(httpGet);
//....do more work...
} catch (SocketTimeoutExcetption | ConnectTimeoutException ex) {
System.out.println("请求连接超时");
} catch (Exception ex) {
System.out.println("请求异常,异常信息:" + ex.getMessage());
}
}

 

Guess you like

Origin www.cnblogs.com/muxi0407/p/11589498.html