apache httpclient 4.5.3 连接配置

本文介绍了一个基于Spring框架的HTTPClient配置方法及其GET和POST请求的具体实现。通过注解配置最大连接数、连接超时时间等参数,并提供了发送JSON格式数据的示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

基于spring,简单的http client 连接配置

import com.google.common.collect.Maps;
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.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Map;

@Service
public class HttpClient {
    private Logger logger = LoggerFactory.getLogger(getClass());
    private CloseableHttpClient httpClient;
    @Value("${http.maxTotal:256}")
    private int maxTotal; // 最大连接数
    @Value("${http.defaultMaxPerRoute:20}")
    private int defaultMaxPerRoute; // 每个路由最大连接
    @Value("${http.connectTimeout:3000}")
    private int connectTimeout; // 连接超时 3秒
    @Value("${http.connectionRequestTimeout:500}")
    private int connectionRequestTimeout; // 从 httpclient 资源池获取httpclient 最多等待500毫秒
    @Value("${http.socketTimeout:30000}")
    private int socketTimeout; // 读取超时 30秒
    @Value("${http.validateAfterInactivity:120000}")
    private int validateAfterInactivity; // 连接闲置2分钟后需要重新检测


    @PostConstruct
    public void initHttpClient() throws IOException {
        PoolingHttpClientConnectionManager httpClientConnectionManager = new PoolingHttpClientConnectionManager();
        httpClientConnectionManager.setMaxTotal(maxTotal);
        httpClientConnectionManager.setDefaultMaxPerRoute(defaultMaxPerRoute);
        httpClientConnectionManager.setValidateAfterInactivity(validateAfterInactivity);

        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
        httpClientBuilder.setConnectionManager(httpClientConnectionManager);

        httpClient = httpClientBuilder.build();
    }

    private RequestConfig.Builder generateConfigBuilder() {
        RequestConfig.Builder builder = RequestConfig.custom();
        builder.setConnectTimeout(connectTimeout)
            .setConnectionRequestTimeout(connectionRequestTimeout)
            .setRedirectsEnabled(false) // 配置禁用30x 跳转
            .setSocketTimeout(socketTimeout)
            .build();
        return builder;
    }

    public String get(final String url) {
        return get(url, 0);
    }

    public String get(final String url, int readTimeOutInMs) {
        final HttpGet get = new HttpGet(url);
        final RequestConfig.Builder configBuilder = generateConfigBuilder();
        if (readTimeOutInMs > 0) configBuilder.setSocketTimeout(readTimeOutInMs);
        get.setConfig(configBuilder.build());
        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(get);
            final String ret = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
            return ret;
        } catch (Exception e) {
            logger.error("get {} error, {}", url, e.getMessage(), e);
            return null;
        } finally {
            try {
                if (response != null) EntityUtils.consume(response.getEntity());
            } catch (IOException ignore) {

            }
        }
    }

    public String postJson(final String url, final Object obj) {
        return postJson(url, obj, 0);
    }

    public String postJson(final String url, final Object obj, int readTimeOutInMs) {
        final Map<String, String> headers = Maps.newHashMap();
        headers.put("Content-Type", "application/json");
        return post(url, JsonUtil.serialize(obj), headers, readTimeOutInMs);
    }

    public String postJson(final String url, final Object obj, Map<String, String> headers) {
        return postJson(url, obj, headers, 0);
    }

    public String postJson(final String url, final Object obj, Map<String, String> headers, int readTimeOutInMs) {
        headers.put("Content-Type", "application/json");
        return post(url, JsonUtil.serialize(obj), headers, readTimeOutInMs);
    }

    public String post(final String url, final String body) {
        return post(url, body, null, 0);
    }

    public String post(final String url, final String body, int readTimeOutInMs) {
        return post(url, body, null, readTimeOutInMs);
    }

    public String post(final String url, final String body, Map<String, String> headers) {
        return post(url, body, headers, 0);
    }

    public String post(final String url, final String body, Map<String, String> headers, int readTimeOutInMs) {
        final HttpPost post = new HttpPost(url);
        final RequestConfig.Builder configBuilder = generateConfigBuilder();
        if (readTimeOutInMs > 0) configBuilder.setSocketTimeout(readTimeOutInMs);
        post.setConfig(configBuilder.build());
        post.setEntity(new StringEntity(body, StandardCharsets.UTF_8));
        if (!CollectionUtils.isEmpty(headers)) headers.forEach((k, v) -> post.addHeader(k, v));
        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(post);
            final String ret = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
            return ret;
        } catch (Exception e) {
            logger.error("post {} error, {}", url, e.getMessage(), e);
            return null;
        } finally {
            try {
                if (response != null) EntityUtils.consume(response.getEntity());
            } catch (IOException ignore) {

            }
        }
    }

}

转载于:https://my.oschina.net/beetlerx/blog/1544421

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值