HttpClient工具类

    @Test
    public void test() {
        String url = "http://dfsns.market.alicloudapi.com/data/send_sms";
        Map<String, Object> body = new HashMap<>();
        body.put("content", "code:" + HttpUtil.getRandomNumber(6));
        body.put("phone_number", "18570892515");
        body.put("template_id", "TPL_0000");

        HashMap<String, Object> header = new HashMap<>();
        header.put("Authorization", "APPCODE 65ed5499417944f1ad101a12014a80c9");
        header.put("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");

        String s = HttpUtil.doPost(url, body, header);
        System.out.println(s);
    }

如果有错的地方或者逻辑bug ,欢迎指出 ,大家一起交流下

package com.atguigu.gulimall.thirdparty.utils;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.*;

/**
 * User: ldj
 * Date: 2022/9/21
 * Time: 5:42
 * Description: HttpUtils
 */

@Slf4j
@Data
public class HttpUtil {

    //私有化构造器
    private HttpUtil() {
    }

    //可以配置到Nacos或配置文件中
    private static final int CONNECT_TIMEOUT = 8000;
    private static final int SOCKET_TIMEOUT = 30000;

    private static final int MAX_TOTAL = 50;
    private static final int MAX_PER_ROUTE = 10;

    private static RequestConfig requestConfig;
    private static PoolingHttpClientConnectionManager connectionManager;


    static {
        //连接池配置
        connectionManager = new PoolingHttpClientConnectionManager();
        connectionManager.setMaxTotal(MAX_TOTAL);              //最大连接数
        connectionManager.setDefaultMaxPerRoute(MAX_PER_ROUTE);//一个服务每次能并行接收的请求数量

        //默认配置参数
        requestConfig = RequestConfig.custom()
                .setConnectionRequestTimeout(CONNECT_TIMEOUT)  //从连接池获取连接最大耗时
                .setConnectTimeout(CONNECT_TIMEOUT)            //访问网站建立连接最大耗时
                .setSocketTimeout(SOCKET_TIMEOUT)              //读取响应数据最大耗时
                .build();
    }

    private static HttpClient getInstant() {
        return HttpClients.custom()
                .setConnectionManager(connectionManager)
                .setDefaultRequestConfig(requestConfig)
                .setRetryHandler(new DefaultHttpRequestRetryHandler(2, false))
                .build();
    }

    //发送get请求
    public static String doGet(String url, Map<String, Object> params) {
        int i = 0;
        String apiUrl = url;
        StringBuilder param = new StringBuilder();

        if (!CollectionUtils.isEmpty(params)) {
            for (String key : params.keySet()) {
                if (i == 0) {
                    param.append("?");
                } else {
                    param.append("&");
                }
                param.append(key).append("=").append(params.get(key));
                i++;
            }
            apiUrl = url + param.toString();
        }
        HttpGet httpGet = new HttpGet(apiUrl);
        HttpResponse response = HttpUtil.execute(httpGet);
        return HttpUtil.dataHandler(url, response);
    }

    //执行get
    public static HttpResponse execute(HttpGet httpGet) {
        try {
            return HttpUtil.getInstant().execute(httpGet);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    //==============================================================================================

    //发送post请求
    public static String doPost(String url, Map<String, Object> body, Map<String, Object> headers) {
        HttpPost httpPost = new HttpPost(url);
        if (!CollectionUtils.isEmpty(headers)) {
            headers.forEach((k, v) -> {
                httpPost.addHeader(k, (String) v);
            });
        }

        if (!CollectionUtils.isEmpty(body)) {
            List<NameValuePair> nameValuePairList = new ArrayList<>();
            body.forEach((k, v) -> {
                nameValuePairList.add(new BasicNameValuePair(k, (String) v));
            });

            //表单Entity
            UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nameValuePairList, StandardCharsets.UTF_8);
            //formEntity.setContentType("application/x-www-form-urlencoded; charset=UTF-8");
            httpPost.setEntity(formEntity);
        }
        HttpResponse execute = HttpUtil.execute(httpPost);
        return HttpUtil.dataHandler(url, execute);
    }

    //执行post
    public static HttpResponse execute(HttpPost httpPost) {
        try {
            return HttpUtil.getInstant().execute(httpPost);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    //数据处理
    private static String dataHandler(String url, HttpResponse response) {

        if (Objects.isNull(response)) {
            log.error("[HttpClientUtil] 请求失败url:[{}],response:[Null]", url);
            return null;
        }

        Integer stateCode = response.getStatusLine().getStatusCode();

        if (!Objects.equals(HttpStatus.SC_OK, stateCode)) {
            log.error("[HttpClientUtil] 请求失败[{}],url:[{}]", stateCode, url);
            return null;
        }

        log.info("[HttpClientUtil] 请求成功[{}],url:[{}]", stateCode, url);

        //TODO 数据检测断点
        HttpEntity responseEntity = response.getEntity();

        if (Objects.nonNull(responseEntity)) {
            try {
                String result = EntityUtils.toString(responseEntity, StandardCharsets.UTF_8);
                log.info("responseEntity:{}", result);
                return result;
            } catch (Exception e) {
                log.error("[EntityUtils] 读取数据异常", e);
            } finally {
                try {
                    EntityUtils.consume(responseEntity);
                } catch (IOException e) {
                    log.error("[EntityUtils] 关闭资源异常", e);
                }
            }
        }
        log.warn("响应数据为Null,请联系第三方");
        return null;
    }

    //生成随机数/验证码
    public static String getRandomNumber(int bit){
        //定义可变字符串
        StringBuilder rs = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < bit; i++) {
            rs.append(random.nextInt(9));
        }
        return rs.toString();
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值