您现在的位置是:首页 > 技术人生 > 后端技术后端技术

httpclient封装HttpUtils

高晓波2021-11-10【后端技术】人已围观

简介开发过程中经常会调用第三方接口,封装httptutils工具方便使用

http统一返回值HttpResult对象:


import lombok.Data;
import org.apache.http.Header;

/**
 * @author gaoxiaobo
 * @description
 * @date 2021/10/28 3:46 下午
 */
@Data
public class HttpResult {
    private int statusCode;

    private Header[] requestHeaders;

    private Header[] responseHeaders;

    private String body;
}

HttpUtils封装:
import com.alibaba.fastjson.JSON;
import org.apache.http.*;
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.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
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.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.ssl.TrustStrategy;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.SSLContext;
import java.nio.charset.StandardCharsets;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.*;

/**
 * @author gaoxiaobo
 * @description
 * @date 2021/9/26 11:17 上午
 */
public class HttpUtils {
    private final static Logger logger = LoggerFactory.getLogger(HttpUtils.class);

    private final static String USER_AGENT = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.131 Safari/537.36";


    public static CloseableHttpClient createSSLClientDefault() {
        try {
            SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
                //信任所有
                public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                    return true;
                }
            }).build();
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);
            return HttpClients.custom().setSSLSocketFactory(sslsf).build();
        } catch (KeyManagementException e) {
            logger.error("错误信息:", e);
        } catch (NoSuchAlgorithmException e) {
            logger.error("错误信息:", e);
        } catch (KeyStoreException e) {
            logger.error("错误信息:", e);
        }
        return HttpClients.createDefault();
    }


    private static RequestConfig requestConfig;

    static {
        requestConfig = RequestConfig.custom()
                .setSocketTimeout(30000)
                .setRedirectsEnabled(true)
                .setConnectTimeout(30000)
                .build();
    }

    public static HttpResult get(String url, Map<String, String> headers, Map<String, Object> params) throws Exception {
        CloseableHttpClient client = HttpClients.createDefault();
        HttpResult result = new HttpResult();
        HttpGet get = null;
        if (params != null && !params.isEmpty()) {
            List<NameValuePair> paramList = new ArrayList<NameValuePair>();

            // 遍历map,设置参数到list中
            for (Map.Entry<String, Object> entry : params.entrySet()) {
                paramList.add(new BasicNameValuePair(entry.getKey(), entry.getValue() == null ? "" : entry.getValue().toString()));
            }

            String paramsStr = EntityUtils.toString(new UrlEncodedFormEntity(paramList, Consts.UTF_8));
            get = new HttpGet(url + "?" + paramsStr);
        } else {
            get = new HttpGet(url);
        }

        get.addHeader("user-agent", USER_AGENT);
        if (headers != null && !headers.isEmpty()) {
            Set<String> keys = headers.keySet();
            for (String key : keys) {
                get.addHeader(key, headers.get(key));
            }
        }

        result.setRequestHeaders(get.getAllHeaders());
        HttpResponse response = client.execute(get);
        result.setResponseHeaders(response.getAllHeaders());
        result.setStatusCode(response.getStatusLine().getStatusCode());

        //5、获取实体
        HttpEntity entity = response.getEntity();
        String s = EntityUtils.toString(entity, "UTF-8");

        result.setBody(s);
        //将实体装成字符串
        return result;
    }

    public static HttpResult get(String url, Map<String, String> headers) throws Exception {
        return get(url, headers, null);
    }

    public static HttpResult get(String url, Object params) throws Exception {
        Map<String, Object> filedsInfo = ReflectUtils.getFiledsInfo(params);
        return get(url, null, filedsInfo);
    }

    public static HttpResult get(String url) throws Exception {
        return get(url, null, null);
    }

    public static HttpResult postFormData(String url, Map<String, Object> params, Map<String, String> headers, String encode) throws Exception {
        HttpResult result = new HttpResult();
        if (encode == null) {
            encode = "utf-8";
        }
        CloseableHttpClient closeableHttpClient = createSSLClientDefault();
        HttpPost httpost = new HttpPost(url);
        httpost.setConfig(requestConfig);

        //设置header
        if (headers != null && headers.size() > 0) {
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                httpost.setHeader(entry.getKey(), entry.getValue());
            }
        }
        result.setRequestHeaders(httpost.getAllHeaders());

        //组织请求参数
        List<NameValuePair> paramList = new ArrayList<NameValuePair>();
        if (params != null && params.size() > 0) {
            Set<String> keySet = params.keySet();
            for (String key : keySet) {
                paramList.add(new BasicNameValuePair(key, params.get(key) == null ? "" : params.get(key).toString()));
            }
        }

        httpost.setEntity(new UrlEncodedFormEntity(paramList, encode));
        CloseableHttpResponse response = closeableHttpClient.execute(httpost);
        result.setResponseHeaders(response.getAllHeaders());
        result.setStatusCode(response.getStatusLine().getStatusCode());

        HttpEntity entity = response.getEntity();
        String s = EntityUtils.toString(entity, encode);

        result.setBody(s);
        return result;
    }

    public static HttpResult postFormData(String url, Map<String, Object> params, Map<String, String> headers) throws Exception{
        return postFormData(url, params, headers, null);
    }

    public static HttpResult postFormData(String url, Object params, Map<String, String> headers) throws Exception{
        Map<String, Object> filedsInfo = ReflectUtils.getFiledsInfo(params);
        return postFormData(url, filedsInfo, headers, null);
    }

    public static HttpResult postFormData(String url, Object params) throws Exception{
        return postFormData(url, params, null);
    }

    public static HttpResult postFormData(String url, Map<String, Object> params) throws Exception{
        return postFormData(url, params, null, null);
    }

    public static HttpResult postFormData(String url) throws Exception{
        return postFormData(url, null, null, null);
    }

    /**
     * POST application/json
     * @param url
     * @param params
     * @param headers
     * @return
     * @throws Exception
     */
    public static HttpResult postJson(String url, Object params, Map<String, String> headers) throws Exception {
        HttpClient client = HttpClients.createDefault();
        HttpResult result = new HttpResult();
        HttpPost post = new HttpPost(url);
        post.setConfig(requestConfig);
        // 构建消息实体
        StringEntity requestEntity = new StringEntity(JSON.toJSONString(params), StandardCharsets.UTF_8);
        requestEntity.setContentEncoding("UTF-8");
        // 发送Json格式的数据请求
        requestEntity.setContentType("application/json");

        //设置header
        if (headers != null && headers.size() > 0) {
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                post.setHeader(entry.getKey(), entry.getValue());
            }
        }

        result.setRequestHeaders(post.getAllHeaders());
        post.setEntity(requestEntity);

        HttpResponse response = client.execute(post);
        result.setResponseHeaders(response.getAllHeaders());
        result.setStatusCode(response.getStatusLine().getStatusCode());

        HttpEntity responseEntity = response.getEntity();
        String resultStr = EntityUtils.toString(responseEntity, "UTF-8");
        result.setBody(resultStr);
        return result;
    }

    public static HttpResult postJson(String url, Object params) throws Exception {
        return postJson(url, params, null);
    }

    public static HttpResult postUrlencodedJson(String url, Object params, Map<String, String> headers) throws Exception {
        Map<String, Object> filedsInfo = ReflectUtils.getFiledsInfo(params);
        return postUrlencodedJson(url, filedsInfo, headers);
    }

    public static HttpResult postUrlencodedJson(String url, Object params) throws Exception {
        Map<String, Object> filedsInfo = ReflectUtils.getFiledsInfo(params);
        return postUrlencodedJson(url, filedsInfo, null);
    }

    /**
     * POST application/x-www-form-urlencoded
     * @param url
     * @param params
     * @param headers
     * @return
     * @throws Exception
     */
    public static HttpResult postUrlencodedJson(String url, Map<String, Object> params, Map<String, String> headers) throws Exception {
        CloseableHttpResponse response = null;
        CloseableHttpClient httpclient = HttpClientBuilder
                .create()
                .build();

        // 创建httppost
        HttpPost httpPost = new HttpPost(url);
        httpPost.setConfig(requestConfig);
        HttpResult result = new HttpResult();

        //设置header
        if (headers != null && headers.size() > 0) {
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                httpPost.setHeader(entry.getKey(), entry.getValue());
            }
        }

        // 设置提交方式
        httpPost.addHeader("Content-type", "application/x-www-form-urlencoded; charset=utf-8");

        // 添加参数
        List<NameValuePair> nameValuePairs = new ArrayList<>();
        if (params.size() != 0) {
            // 将mapdata中的key存在set集合中,通过迭代器取出所有的key,再获取每一个键对应的值
            Set<String> keySet = params.keySet();
            for (String key : keySet) {
                String v = params.get(key) == null ? "" : params.get(key).toString();// value
                nameValuePairs.add(new BasicNameValuePair(key, v));
            }
        }
        UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(nameValuePairs, "UTF-8");
        httpPost.setEntity(urlEncodedFormEntity);

        result.setRequestHeaders(httpPost.getAllHeaders());
        // 执行http请求
        response = httpclient.execute(httpPost);
        result.setResponseHeaders(response.getAllHeaders());
        result.setStatusCode(response.getStatusLine().getStatusCode());

        // 获得http响应体
        HttpEntity entity = response.getEntity();
        String s = EntityUtils.toString(entity, "UTF-8");
        result.setBody(s);
        return result;
    }

}

Tags:

很赞哦! ()

上一篇:SpringBoot添加XSS过滤器

下一篇:返回列表

文章评论