HttpClient如何进行RequestConfig的相关配置呢?
下文笔者讲述基于HttpClient的RequestConfig配置的示例分享,如下所示:
RequestConfig是httpClient中用于连接设置的对象 下文笔者将通过示例的方式,讲述RequestConfig的配置案例,如下所示:例:
public void requestConfig(){
// 新建一个RequestConfig:
RequestConfig defaultRequestConfig = RequestConfig.custom()
//一、连接目标服务器超时时间:ConnectionTimeout-->指的是连接一个url的连接等待时间
.setConnectTimeout(5000)
//二、读取目标服务器数据超时时间:SocketTimeout-->指的是连接上一个url,获取response的返回等待时间
.setSocketTimeout(5000)
//三、从连接池获取连接的超时时间:ConnectionRequestTimeout
.setConnectionRequestTimeout(5000)
.build();
// 这个超时可以设置为客户端级别,作为所有请求的默认值:
CloseableHttpClient httpclient = HttpClients.custom()
.setDefaultRequestConfig(defaultRequestConfig)
.build();
// httpclient.execute(httppost);的时候可以让httppost直接享受到httpclient中的默认配置.
// Request不会继承客户端级别的请求配置,所以在自定义Request的时候,需要将客户端的默认配置拷贝过去:
HttpGet httpget = new HttpGet("http://www.apache.org/");
RequestConfig requestConfig = RequestConfig.copy(defaultRequestConfig)
.setProxy(new HttpHost("myotherproxy", 8080))
.build();
httpget.setConfig(requestConfig);
// httpget可以单独地使用新copy的requestConfig请求配置,不会对别的request请求产生影响
}
参考资料:http://www.java265.com/JavaCourse/202204/2934.html HttpUtils工具类
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


