HttpClient如何使用RequestConfig设置连接超时,请求超时,读取超时呢?

书欣 Java经验 发布时间:2022-08-28 21:53:36 阅读数:15176 1 HttpClient
下文笔者讲述HttpClient中设置各种超时的方法分享,如下所示

未设置超时前的方法

public static HttpResponse doGet(String host, String path,
                                     Map<String, String> headers,
                                     Map<String, String> querys)
            throws Exception {
        HttpClient httpClient = wrapClient(host,path);
        HttpGet request = new HttpGet(buildUrl(host, path, querys));
        for (Map.Entry<String, String> e : headers.entrySet()) {
            request.addHeader(e.getKey(), e.getValue());
        }
        return httpClient.execute(request);
    }

设置超时后的方法

public static HttpResponse doGet(String host, String path,
                                     Map<String, String> headers,
                                     Map<String, String> querys)
            throws Exception {
        HttpClient httpClient = wrapClient(host,path);
        HttpGet request = new HttpGet(buildUrl(host, path, querys));
        for (Map.Entry<String, String> e : headers.entrySet()) {
            request.addHeader(e.getKey(), e.getValue());
        }
        request.setConfig(setTimeOutConfig(request.getConfig()));
        return httpClient.execute(request);
    }
/**
 * 设置 连接超时、 请求超时 、 读取超时  毫秒
 * @param requestConfig
 * @return
 */
private static RequestConfig setTimeOutConfig(RequestConfig requestConfig){
	return RequestConfig.copy(requestConfig)
			.setConnectionRequestTimeout(60000)
			.setConnectTimeout(60000)
			.setSocketTimeout(10000)
			.build();
}
版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

本文链接: https://www.Java265.com/JavaJingYan/202208/16616948724274.html

最近发表

热门文章

好文推荐

Java265.com

https://www.java265.com

站长统计|粤ICP备14097017号-3

Powered By Java265.com信息维护小组

使用手机扫描二维码

关注我们看更多资讯

java爱好者