CloseableHttpClient设置超时

Posted muxi0407

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了CloseableHttpClient设置超时相关的知识,希望对你有一定的参考价值。

Java开发我们常常需要和第三方系统进行通信,通信的方式有多种,如dubbo方式,webservice,微服务和CloseableHttpClient等方式,常涉及到超时问题,这里主要说的是CloseableHttpClient的超时设置以及超市了的异常处理;一般思路就是,

1,定义超时的时间,这个一般作为一个配置项,方便随时修改;

2,请求配置对象RequestConfig设置超时时间,然后设置到 HttpGet 或 HttpPost 请求方法对象;

3,使用CloseableHttpClient对象执行相应的请求方法,同时使用 try...catch... 捕获异常,对于超时可通过 SocketTimeoutExcetption 和 ConnectTimeoutException捕获异常;

例如下面简要例子(相应的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());


 

以上是关于CloseableHttpClient设置超时的主要内容,如果未能解决你的问题,请参考以下文章

httpclient: 设置请求的超时时间,连接超时时间等

Apache HttpClient API 中的 CloseableHttpClient 和 HttpClient 有啥区别?

错误:连接超时:连接

CloseableHttpClient post调用示例

httpClient4.5 closeableHttpClient用法

CloseableHttpClient报java.net.SocketTimeoutException: Read timed out的解决方法