将HttpClient5封装成Http请求工具类

1 篇文章 0 订阅

将HttpClient5封装成Http请求工具类

引入依赖

<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents.client5/httpclient5 -->
<dependency>
    <groupId>org.apache.httpcomponents.client5</groupId>
    <artifactId>httpclient5</artifactId>
    <version>${httpclient5.version}</version>
</dependency>

HttpUtil.java工具类

import cn.hutool.core.codec.Base64;
import com.opene.module.fedex.bean.dto.FedexRequestHeader;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.classic.methods.HttpPut;
import org.apache.hc.client5.http.config.RequestConfig;
import org.apache.hc.client5.http.entity.UrlEncodedFormEntity;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.ContentType;
import org.apache.hc.core5.http.NameValuePair;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.io.entity.StringEntity;
import org.apache.hc.core5.http.message.BasicNameValuePair;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
public class HttpUtil {
    private HttpUtil(){}

    /** 超时时间5分钟 **/
    private static final int milliseconds = 300000;

    private final static String TOKEN_NAME = "lvt_token=";

    /**
     * post请求
     * @param url
     * @param body
     * @return HttpResult
     */
    public static HttpResult post(String url, String body) {
        log.info("\nPOST请求URL:{} \n bodyData:{}", url, body);
        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("Content-Type", ContentType.APPLICATION_JSON);
        httpPost.setEntity(new StringEntity(body, ContentType.APPLICATION_JSON));
        try (CloseableHttpClient httpclient = HttpClients.custom().setDefaultRequestConfig(getRequestConfig()).build()) {
            try (CloseableHttpResponse response = httpclient.execute(httpPost)) {
                String bodyData = StringUtils.toEncodedString(EntityUtils.toByteArray(response.getEntity()), StandardCharsets.UTF_8);
                log.info("\nPOST请求返回结果,status:{},body:{}", response.getCode(), bodyData);
                return HttpResult.setParams(response.getCode(), bodyData);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * post请求
     * @param url
     * @param userName
     * @param password
     * @return HttpResult
     */
    public static HttpResult post(String url, String userName, String password) {
        log.info("\nPOST请求URL:{} \n userName:{} \n password:{}", url, userName, password);
        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("Authorization", "Basic " + Base64.encode(userName + ":" + password));
        try (CloseableHttpClient httpclient = HttpClients.custom().setDefaultRequestConfig(getRequestConfig()).build()) {
            try (CloseableHttpResponse response = httpclient.execute(httpPost)) {
                String bodyData = StringUtils.toEncodedString(EntityUtils.toByteArray(response.getEntity()), StandardCharsets.UTF_8);
                log.info("\nPOST请求返回结果,status:{},body:{}", response.getCode(), bodyData);
                return HttpResult.setParams(response.getCode(), bodyData);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * post请求
     * @param url
     * @param userName
     * @param password
     * @param paramMap
     * @return HttpResult
     */
    public static HttpResult postForm(String url, String userName, String password, Map<String, String> paramMap) {
        log.info("\nPOST请求URL:{} \n bodyData:{}", url, paramMap);

        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
        httpPost.setHeader("Authorization", "Basic " + Base64.encode(userName + ":" + password));
        httpPost.setEntity(getFormEntity(paramMap));
        try (CloseableHttpClient httpclient = HttpClients.custom().setDefaultRequestConfig(getRequestConfig()).build()) {
            try (CloseableHttpResponse response = httpclient.execute(httpPost)) {
                String bodyData = StringUtils.toEncodedString(EntityUtils.toByteArray(response.getEntity()), StandardCharsets.UTF_8);
                log.info("\nPOST请求返回结果,status:{},body:{}", response.getCode(), bodyData);
                return HttpResult.setParams(response.getCode(), bodyData);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 封装Post请求的form表单
     * @param paramMap
     * @return UrlEncodedFormEntity
     */
    private static UrlEncodedFormEntity getFormEntity(Map<String, String> paramMap){
        //参数定义
        List<NameValuePair> params = new ArrayList<>();
        if(!CollectionUtils.isEmpty(paramMap)){
            paramMap.forEach((k, v) -> {
                params.add(new BasicNameValuePair(k, v));
            });
            //创建提交的表单对象
            return new UrlEncodedFormEntity(params, StandardCharsets.UTF_8);
        }
        return new UrlEncodedFormEntity(params);
    }

    /**
     * post请求
     * @param url   地址
     * @param paramMap  请求参数
     * @return  HttpResult
     */
    public static HttpResult post(String url, Map<String, String> paramMap) {
        log.info("\nPOST请求URL:{} \n bodyData:{}", url, paramMap);

        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
        httpPost.setEntity(getFormEntity(paramMap));
        try (CloseableHttpClient httpclient = HttpClients.custom().setDefaultRequestConfig(getRequestConfig()).build()) {
            try (CloseableHttpResponse response = httpclient.execute(httpPost)) {
                String bodyData = StringUtils.toEncodedString(EntityUtils.toByteArray(response.getEntity()), StandardCharsets.UTF_8);
                log.info("\nPOST请求返回结果,status:{},body:{}", response.getCode(), bodyData);
                return HttpResult.setParams(response.getCode(), bodyData);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * post请求
     * @param url   地址
     * @param requestHeader 请求头参数
     * @param body  请求参数
     * @return  HttpResult
     */
    public static HttpResult post(String url, FedexRequestHeader requestHeader, String body) {
        log.info("\nPOST请求URL:{} \n requestHeader:{} \n bodyData:{}", url, requestHeader, body);

        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("Authorization", "Bearer " + requestHeader.getAuthorization());
        httpPost.setHeader("Content-Type", requestHeader.getContentType());
        httpPost.setHeader("X-locale", requestHeader.getXlocale());
        httpPost.setHeader("x-customer-transaction-id", requestHeader.getCustomerTransactionId());
        httpPost.setEntity(new StringEntity(body, ContentType.APPLICATION_JSON));
        try (CloseableHttpClient httpclient = HttpClients.custom().setDefaultRequestConfig(getRequestConfig()).build()) {
            try (CloseableHttpResponse response = httpclient.execute(httpPost)) {
                String bodyData = StringUtils.toEncodedString(EntityUtils.toByteArray(response.getEntity()), StandardCharsets.UTF_8);
                log.info("\nPOST请求返回结果,status:{},body:{}", response.getCode(), bodyData);
                return HttpResult.setParams(response.getCode(), bodyData);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * put请求
     * @param url   地址
     * @param requestHeader 请求头参数
     * @param body  请求参数
     * @return  HttpResult
     */
    public static HttpResult put(String url, FedexRequestHeader requestHeader, String body) {
        log.info("\nPUT请求URL:{} \n requestHeader:{} \n bodyData:{}", url, requestHeader, body);

        HttpPut httpPut = new HttpPut(url);
        httpPut.setHeader("Authorization", "Bearer " + requestHeader.getAuthorization());
        httpPut.setHeader("Content-Type", requestHeader.getContentType());
        httpPut.setHeader("X-locale", requestHeader.getXlocale());
        httpPut.setHeader("x-customer-transaction-id", requestHeader.getCustomerTransactionId());
        httpPut.setEntity(new StringEntity(body, ContentType.APPLICATION_JSON));
        try (CloseableHttpClient httpclient = HttpClients.custom().setDefaultRequestConfig(getRequestConfig()).build()) {
            try (CloseableHttpResponse response = httpclient.execute(httpPut)) {
                String bodyData = StringUtils.toEncodedString(EntityUtils.toByteArray(response.getEntity()), StandardCharsets.UTF_8);
                log.info("\nPUT请求返回结果,status:{},body:{}", response.getCode(), bodyData);
                return HttpResult.setParams(response.getCode(), bodyData);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * get请求
     * @param url
     * @return
     */
    public static HttpResult httpClientGet(String url) {
        log.info("\nGET请求URL:{}", url);

        HttpGet httpGet = new HttpGet(url);
        try (CloseableHttpClient httpclient = HttpClients.custom().setDefaultRequestConfig(getRequestConfig()).build()) {
            try (CloseableHttpResponse response = httpclient.execute(httpGet)) {
                String bodyData = StringUtils.toEncodedString(EntityUtils.toByteArray(response.getEntity()), StandardCharsets.UTF_8);
                log.info("\nGET请求返回结果,status:{},body:{}", response.getCode(), bodyData);
                return HttpResult.setParams(response.getCode(), bodyData);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * get请求
     * @param url
     * @param token
     * @return  HttpResult
     */
    public static HttpResult httpClientGet(String url, String token) {
        log.info("\nGET请求URL:{} ,token:{}", url,token);

        HttpGet httpGet = new HttpGet(url);
        httpGet.addHeader("cookie",TOKEN_NAME + token);
        httpGet.setHeader("Authorization", "Bearer " + token);
        try (CloseableHttpClient httpclient = HttpClients.custom().setDefaultRequestConfig(getRequestConfig()).build()) {
            try (CloseableHttpResponse response = httpclient.execute(httpGet)) {
                String bodyData = StringUtils.toEncodedString(EntityUtils.toByteArray(response.getEntity()), StandardCharsets.UTF_8);
                log.info("\nGET请求返回结果,status:{},body:{}", response.getCode(), bodyData);
                return HttpResult.setParams(response.getCode(), bodyData);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * get请求
     * @param url
     * @param userName
     * @param password
     * @return  HttpResult
     */
    public static HttpResult httpClientGet(String url, String userName, String password){
        log.info("\nGET请求URL:{}", url);

        HttpGet httpGet = new HttpGet(url);
        httpGet.addHeader("Authorization", "Basic " + Base64.encode(userName + ":" + password));
        try (CloseableHttpClient httpclient = HttpClients.custom().setDefaultRequestConfig(getRequestConfig()).build()) {
            try (CloseableHttpResponse response = httpclient.execute(httpGet)) {
                String bodyData = StringUtils.toEncodedString(EntityUtils.toByteArray(response.getEntity()), StandardCharsets.UTF_8);
                log.info("\nGET请求返回结果,status:{},body:{}", response.getCode(), bodyData);
                return HttpResult.setParams(response.getCode(), bodyData);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private static RequestConfig getRequestConfig() {
        return RequestConfig.custom()
                .setConnectTimeout(milliseconds, TimeUnit.MILLISECONDS)
                .setResponseTimeout(milliseconds, TimeUnit.MILLISECONDS)
                .setConnectionRequestTimeout(milliseconds, TimeUnit.MILLISECONDS)
                .build();
    }


    /**
     * get请求自动组装参数
     * @param url
     * @param paramMap
     * @param userName
     * @param password
     * @return  HttpResult
     */
    public static HttpResult httpClientGet(String url, Map<String, Object> paramMap, String userName, String password) {
        return httpClientGet(assemblyGetUrl(url, paramMap), userName, password);
    }

    /**
     * get请求自动组装参数
     * @param url
     * @param paramMap
     * @return HttpResult
     */
    public static HttpResult httpClientGet(String url, Map<String, Object> paramMap) {
        return httpClientGet(assemblyGetUrl(url, paramMap));
    }

    public static String assemblyGetUrl(String url, Map<String, Object> paramMap) {
        StringBuffer sb = new StringBuffer(url);
        boolean first = true;
        for (Map.Entry<String, Object> entry : paramMap.entrySet()) {
            if(first) {
                sb.append("?");
            } else {
                sb.append("&");
            }
            sb.append(entry.getKey());
            sb.append("=");
            sb.append(entry.getValue());
            first = false;
        }
        return sb.toString();
    }
}


暂时没用到的类

import org.apache.hc.client5.http.config.RequestConfig;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManager;

import java.util.concurrent.TimeUnit;

public class HttpClientConfig {

    /** 超时时间5分钟 **/
    private static final int milliseconds = 300000;

    public static CloseableHttpClient getHttpClient(){
        // 创建连接池
        PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
        // 设置最大连接数
        connectionManager.setMaxTotal(100);
        // 设置每个主机地址的并发数
        connectionManager.setDefaultMaxPerRoute(30);

        //2.创建httpclient对象
        return HttpClients.custom()
                .setConnectionManager(connectionManager)
                .setDefaultRequestConfig(getRequestConfig())
                .build();
    }

    private static RequestConfig getRequestConfig() {
        return RequestConfig.custom()
                .setConnectTimeout(milliseconds, TimeUnit.MILLISECONDS)
                .setResponseTimeout(milliseconds, TimeUnit.MILLISECONDS)
                .setConnectionRequestTimeout(milliseconds, TimeUnit.MILLISECONDS)
                .build();
    }
}

其他

httpclient连接池配置以及请求方式示例:


欢迎关注公众号:慌途L
后面会慢慢将文章迁移至公众号,也是方便在没有电脑的情况下可以进行翻阅,更新的话会两边同时更新,大家不用担心!
在这里插入图片描述


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值