Apache HttpClient 4.5设置超时时间

简介: Apache HttpClient 4.5设置超时时间
前言

这是个3.X的超时设置方法

HttpClient client = newHttpClient();
client.setConnectionTimeout(30000); 
client.setTimeout(30000);

还可以这样

HttpClient httpClient = newHttpClient(); 
httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(3000);

4.X版本的超时设置(4.3之前版本)

HttpClient httpClient=newDefaultHttpClient();
httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,2000);//连接时间
httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,2000);//数据传输时间

4.3及以后版本的超时设置

CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = newHttpGet(url);
RequestConfig config = RequestConfig.custom().setConnectTimeout(2000).setConnectionRequestTimeout(1000).setSocketTimeout(2000).build();
httpGet.setConfig(config);
示例

下面以4.5版写一个例子:

所需jar包

<!-- httpclient-->
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.2</version>
</dependency>
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpmime</artifactId>
    <version>4.3.1</version>
</dependency>

示例代码

package com.site.utils;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
/**
 * 网络请求工具类
 */
public class HttpUtil {
    private static Logger logger = LoggerFactory.getLogger(HttpUtil.class);    //日志记录
    /**
     * post请求
     *
     * @param url      url地址
     * @param paramMap 参数
     * @return
     */
    public static String httpPost(String url,Map<String, String> paramMap) {
        logger.info("post url-->" + url);
        try {
            CloseableHttpClient httpClient = HttpClients.createDefault();
            HttpPost httpPost = new HttpPost(url);
            //设置超时          
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(5000).setConnectionRequestTimeout(1000).setSocketTimeout(5000).build();
            httpPost.setConfig(requestConfig);
            //设置请求参数
            if (!paramMap.isEmpty()) {
                List<NameValuePair> list = new LinkedList<>();
                for (Map.Entry<String, String> entry : paramMap.entrySet()) {
                    list.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
                }
                UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(list, "UTF-8");
                httpPost.setEntity(formEntity);
            }
            CloseableHttpResponse result = httpClient.execute(httpPost);
            String response = EntityUtils.toString(result.getEntity(), "UTF-8");
            logger.info("response-->" + response);
            return response;
        } catch (IOException e) {
            logger.error("post请求失败:", e);
        }
        return null;
    }
    /**
     * 发送get请求
     *
     * @param url 路径
     * @return
     */
    public static String httpGet(String url) {
        logger.info("get url-->" + url);
        try {
            CloseableHttpClient client = HttpClients.createDefault();
            //发送get请求
            HttpGet request = new HttpGet(url);
            //设置超时          
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(5000).setConnectionRequestTimeout(1000).setSocketTimeout(5000).build();
            request.setConfig(requestConfig);
            CloseableHttpResponse response = client.execute(request);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                /**请求发送成功,并得到响应**/
                String resp = EntityUtils.toString(response.getEntity(), "UTF-8");
                logger.info("response-->" + resp);
                return StringUtils.isBlank(resp) ? "OK" : resp;
            }
        } catch (IOException e) {
            logger.error("get请求提交失败:", e);
        }
        return null;
    }
}
  • setConnectTimeout :设置连接超时时间,单位毫秒。
  • setConnectionRequestTimeout :设置从connect Manager获取Connection 超时时间,单位毫秒。这个属性是新加的属性,因为目前版本是可以共享连接池的。
  • setSocketTimeout :请求获取数据的超时时间,单位毫秒。 如果访问一个接口,多少时间内无法返回数据,就直接放弃此次调用。

参考:

https://www.cnblogs.com/warehouse/p/6879395.html

https://blog.csdn.net/z69183787/article/details/78039601/

相关文章
|
5月前
|
JSON 前端开发 API
Apache HttpClient调用Spring3 MVC Restful Web API演示
Apache HttpClient调用Spring3 MVC Restful Web API演示
43 1
|
6月前
|
JSON Java Apache
Spring Cloud Feign 使用Apache的HTTP Client替换Feign原生httpclient
Spring Cloud Feign 使用Apache的HTTP Client替换Feign原生httpclient
370 0
|
6月前
|
数据采集 前端开发 Java
利用Scala与Apache HttpClient实现网络音频流的抓取
利用Scala与Apache HttpClient实现网络音频流的抓取
|
6月前
|
数据采集 安全 Java
Kotlin+Apache HttpClient+代理服务器=高效的eBay图片爬虫
本文将为你介绍一种高效的eBay图片爬虫的实现方式,让你可以用Kotlin+Apache HttpClient+代理服务器的组合来轻松地下载eBay的图片。
Kotlin+Apache HttpClient+代理服务器=高效的eBay图片爬虫
|
6月前
|
消息中间件 Kafka Apache
Apache Flink消费Kafka数据时,可以通过设置`StreamTask.setInvokingTaskNumber`方法来实现限流
Apache Flink消费Kafka数据时,可以通过设置`StreamTask.setInvokingTaskNumber`方法来实现限流
166 1
|
Arthas Java 测试技术
一次NSF FeignClient支持Apache HttpClient的优化
一次NSF FeignClient支持Apache HttpClient的优化
292 2
|
消息中间件 缓存 容灾
Apache Kafka-通过设置Consumer Group实现广播模式
Apache Kafka-通过设置Consumer Group实现广播模式
1907 0
|
Java Apache Maven
Apache HttpComponents 之 Httpclient 参考
Apache HttpComponents Apache HttpComponents 项目负责创建和维护一个基于 HTTP 和相关协议的底层 Java 组件工具集。
592 0
Apache HttpComponents 之 Httpclient 参考
|
Apache PHP
【PHP编程之路-1】设置apache虚拟目录
【PHP编程之路-1】设置apache虚拟目录
396 0
【PHP编程之路-1】设置apache虚拟目录
|
Apache
apache 设置.htaccess 禁止ip访问
网站遭受攻击,拦截ip访问
300 0

推荐镜像

更多