首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >封装httpClient工具类进行get、post、put、delete的http接口请求,可添加请求头与参数,支持多线程

封装httpClient工具类进行get、post、put、delete的http接口请求,可添加请求头与参数,支持多线程

作者头像
全栈程序员站长
发布2022-09-18 14:48:31
发布2022-09-18 14:48:31
2.9K00
代码可运行
举报
运行总次数:0
代码可运行

大家好,又见面了,我是你们的朋友全栈君。

首先需要json以及httpclient的maven依赖:

代码语言:javascript
代码运行次数:0
运行
复制
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.62</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.13</version>
        </dependency>

spring下自动添加token以及支持多线程:

代码语言:javascript
代码运行次数:0
运行
复制
package com.supcon.mare.oms.util.test;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.LayeredConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
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.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.net.ssl.SSLContext;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.net.URI;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @author: zhaoxu
 * @description:
 */
public class HttpClientUtil { 
   
    private static Logger LOGGER = LoggerFactory.getLogger(HttpClientUtil.class);
    private static PoolingHttpClientConnectionManager cm = null;
    private static RequestConfig requestConfig = null;

    static { 
   

        LayeredConnectionSocketFactory sslsf = null;
        try { 
   
            sslsf = new SSLConnectionSocketFactory(SSLContext.getDefault());
        } catch (NoSuchAlgorithmException e) { 
   
            LOGGER.error("创建SSL连接失败");
        }
        Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("https", sslsf)
                .register("http", new PlainConnectionSocketFactory())
                .build();
        cm = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
        //多线程调用注意配置,根据线程数设定
        cm.setMaxTotal(200);
        //多线程调用注意配置,根据线程数设定
        cm.setDefaultMaxPerRoute(300);
        requestConfig = RequestConfig.custom()
                //数据传输过程中数据包之间间隔的最大时间
                .setSocketTimeout(20000)
                //连接建立时间,三次握手完成时间
                .setConnectTimeout(20000)
                //重点参数
                .setExpectContinueEnabled(true)
                .setConnectionRequestTimeout(10000)
                //重点参数,在请求之前校验链接是否有效
                .setStaleConnectionCheckEnabled(true)
                .build();
    }

    public static CloseableHttpClient getHttpClient() { 
   
        CloseableHttpClient httpClient = HttpClients.custom()
                .setConnectionManager(cm)
                .build();
        return httpClient;
    }

    public static void closeResponse(CloseableHttpResponse closeableHttpResponse) throws IOException { 
   
        EntityUtils.consume(closeableHttpResponse.getEntity());
        closeableHttpResponse.close();
    }

    /**
     * get请求,params可为null,headers可为null
     *
     * @param headers
     * @param url
     * @return
     * @throws IOException
     */
    public static String get(JSONObject headers, String url, JSONObject params) throws IOException { 
   
        CloseableHttpClient httpClient = getHttpClient();
        CloseableHttpResponse closeableHttpResponse = null;
        // 创建get请求
        HttpGet httpGet = null;
        List<BasicNameValuePair> paramList = new ArrayList<>();
        if (params != null) { 
   
            Iterator<String> iterator = params.keySet().iterator();
            while (iterator.hasNext()) { 
   
                String paramName = iterator.next();
                paramList.add(new BasicNameValuePair(paramName, params.get(paramName).toString()));
            }
        }
        if (url.contains("?")) { 
   
            httpGet = new HttpGet(url + "&" + EntityUtils.toString(new UrlEncodedFormEntity(paramList, Consts.UTF_8)));
        } else { 
   
            httpGet = new HttpGet(url + "?" + EntityUtils.toString(new UrlEncodedFormEntity(paramList, Consts.UTF_8)));
        }

        if (headers != null) { 
   
            Iterator iterator = headers.keySet().iterator();
            while (iterator.hasNext()) { 
   
                String headerName = iterator.next().toString();
                httpGet.addHeader(headerName, headers.get(headerName).toString());
            }
        } else { 
   
            HttpServletRequest request = ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getRequest();
            if (request.getHeader(ClosedPathConstants.TOKEN) != null) { 
   
                String token = request.getHeader(ClosedPathConstants.TOKEN);
                httpGet.addHeader(ClosedPathConstants.TOKEN, token);
            }
        }
        httpGet.setConfig(requestConfig);
        httpGet.addHeader("Content-Type", "application/json");
        httpGet.addHeader("lastOperaTime", String.valueOf(System.currentTimeMillis()));
        closeableHttpResponse = httpClient.execute(httpGet);
        HttpEntity entity = closeableHttpResponse.getEntity();
        String response = EntityUtils.toString(entity);
        closeResponse(closeableHttpResponse);
        return response;
    }

    /**
     * post请求,params可为null,headers可为null
     *
     * @param headers
     * @param url
     * @param params
     * @return
     * @throws IOException
     */
    public static String post(JSONObject headers, String url, JSONObject params) throws IOException { 
   
        CloseableHttpClient httpClient = getHttpClient();
        CloseableHttpResponse closeableHttpResponse = null;
        // 创建post请求
        HttpPost httpPost = new HttpPost(url);
        if (headers != null) { 
   
            Iterator iterator = headers.keySet().iterator();
            while (iterator.hasNext()) { 
   
                String headerName = iterator.next().toString();
                httpPost.addHeader(headerName, headers.get(headerName).toString());
            }
        } else { 
   
            HttpServletRequest request = ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getRequest();
            if (request.getHeader(ClosedPathConstants.TOKEN) != null) { 
   
                String token = request.getHeader(ClosedPathConstants.TOKEN);
                httpPost.addHeader(ClosedPathConstants.TOKEN, token);
            }
        }
        httpPost.setConfig(requestConfig);
        httpPost.addHeader("Content-Type", "application/json");
        httpPost.addHeader("lastOperaTime", String.valueOf(System.currentTimeMillis()));
        if (params != null) { 
   
            StringEntity stringEntity = new StringEntity(params.toJSONString(), "UTF-8");
            httpPost.setEntity(stringEntity);
        }
        closeableHttpResponse = httpClient.execute(httpPost);
        HttpEntity entity = closeableHttpResponse.getEntity();
        String response = EntityUtils.toString(entity);
        closeResponse(closeableHttpResponse);
        return response;
    }

    /**
     * delete,params可为null,headers可为null
     *
     * @param url
     * @param params
     * @return
     * @throws IOException
     */
    public static String delete(JSONObject headers, String url, JSONObject params) throws IOException { 
   
        CloseableHttpClient httpClient = getHttpClient();
        CloseableHttpResponse closeableHttpResponse = null;
        // 创建delete请求,HttpDeleteWithBody 为内部类,类在下面
        HttpDeleteWithBody httpDelete = new HttpDeleteWithBody(url);
        if (headers != null) { 
   
            Iterator iterator = headers.keySet().iterator();
            while (iterator.hasNext()) { 
   
                String headerName = iterator.next().toString();
                httpDelete.addHeader(headerName, headers.get(headerName).toString());
            }
        } else { 
   
            HttpServletRequest request = ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getRequest();
            if (request.getHeader(ClosedPathConstants.TOKEN) != null) { 
   
                String token = request.getHeader(ClosedPathConstants.TOKEN);
                httpDelete.addHeader(ClosedPathConstants.TOKEN, token);
            }
        }
        httpDelete.setConfig(requestConfig);
        httpDelete.addHeader("Content-Type", "application/json");
        httpDelete.addHeader("lastOperaTime", String.valueOf(System.currentTimeMillis()));
        if (params != null) { 
   
            StringEntity stringEntity = new StringEntity(params.toJSONString(), "UTF-8");
            httpDelete.setEntity(stringEntity);
        }
        closeableHttpResponse = httpClient.execute(httpDelete);
        HttpEntity entity = closeableHttpResponse.getEntity();
        String response = EntityUtils.toString(entity);
        closeResponse(closeableHttpResponse);
        return response;
    }

    /**
     * put,params可为null,headers可为null
     *
     * @param url
     * @param params
     * @return
     * @throws IOException
     */
    public static String put(JSONObject headers, String url, JSONObject params) throws IOException { 
   
        CloseableHttpClient httpClient = getHttpClient();
        CloseableHttpResponse closeableHttpResponse = null;
        // 创建put请求
        HttpPut httpPut = new HttpPut(url);
        if (headers != null) { 
   
            Iterator iterator = headers.keySet().iterator();
            while (iterator.hasNext()) { 
   
                String headerName = iterator.next().toString();
                httpPut.addHeader(headerName, headers.get(headerName).toString());
            }
        } else { 
   
            HttpServletRequest request = ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getRequest();
            if (request.getHeader(ClosedPathConstants.TOKEN) != null) { 
   
                String token = request.getHeader(ClosedPathConstants.TOKEN);
                httpPut.addHeader(ClosedPathConstants.TOKEN, token);
            }
        }
        httpPut.setConfig(requestConfig);
        httpPut.addHeader("Content-Type", "application/json");
        httpPut.addHeader("lastOperaTime", String.valueOf(System.currentTimeMillis()));
        if (params != null) { 
   
            StringEntity stringEntity = new StringEntity(params.toJSONString(), "UTF-8");
            httpPut.setEntity(stringEntity);
        }
        // 从响应模型中获得具体的实体
        closeableHttpResponse = httpClient.execute(httpPut);
        HttpEntity entity = closeableHttpResponse.getEntity();
        String response = EntityUtils.toString(entity);
        closeResponse(closeableHttpResponse);
        return response;
    }

    public static class HttpDeleteWithBody extends HttpEntityEnclosingRequestBase { 
   
        public static final String METHOD_NAME = "DELETE";

        @Override
        public String getMethod() { 
   
            return METHOD_NAME;
        }

        public HttpDeleteWithBody(final String uri) { 
   
            super();
            setURI(URI.create(uri));
        }

        public HttpDeleteWithBody(final URI uri) { 
   
            super();
            setURI(uri);
        }

        public HttpDeleteWithBody() { 
   
            super();
        }
    }
}

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/157763.html原文链接:https://javaforall.cn

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档