http请求工具类HttpClientUtil(get使用body,post乱码问题解决)_((httpentityenclosingrequestbase) httppost.setenti-程序员宅基地

技术标签: 后端  httpclient  

最近很多发送http请求的需求存在,书写下util

1:配置需要的依赖

在pom.xml中配置http相关依赖

		<dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpclient</artifactId>
			<scope>compile</scope>
		</dependency>
		<dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpcore</artifactId>
		</dependency>

2:因部分特殊(蠢狗)对接方需要get请求使用body请求体,附上重写的类

/**
 * @author afresh
 * @description 封装httpget可以携带body参数
 * @since 2020/2/25 11:08 上午
 */
public class HttpGetWithBody extends HttpEntityEnclosingRequestBase {

    public static final String METHOD_NAME = "GET";

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

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

若其他请求例如delete也需要使用body请求体,则将METHD_NAME改为对应的值即可 例如:“DELETE”

3:完整util代码 可直接使用

注意一点:常见的post请求乱码问题需要使用 下述代码(只设置CONTENT_TYPE的编码格式不生效)

httpPost.setEntity(new StringEntity(param, ContentType.create("application/json", "utf-8")));
public class HttpCommonClientUtils {

    private static PoolingHttpClientConnectionManager pccm= null;

    private static final Logger logger = LoggerFactory.getLogger(HttpCommonClientUtils.class);

    private static final String CONTENT_TYPE = "application/json;charset=utf-8";

    static {
        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);
            Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
                    .register("http", PlainConnectionSocketFactory.getSocketFactory())
                    .register("https", sslsf)
                    .build();

            pccm = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
            pccm.setDefaultMaxPerRoute(30); //每个主机的最大并行链接数
            pccm.setMaxTotal(200);
        } catch (KeyManagementException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (KeyStoreException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取连接
     * @return
     */
    private static HttpClient getHttpClient() {

        //设置连接超时时间
        int REQUEST_TIMEOUT = 20*1000;  //设置请求超时20秒钟
        int SO_TIMEOUT = 20*1000;       //设置等待数据超时时间20秒钟
        RequestConfig defaultRequestConfig = RequestConfig.custom()
                .setSocketTimeout(SO_TIMEOUT)
                .setConnectTimeout(REQUEST_TIMEOUT)
                .setConnectionRequestTimeout(REQUEST_TIMEOUT)
                .setStaleConnectionCheckEnabled(true)
                .build();

        CloseableHttpClient httpClient = HttpClients.custom()
                .setConnectionManager(pccm).setDefaultRequestConfig(defaultRequestConfig).build();
        return httpClient;
    }

    /**
     * 发起请求并返回结果POST
     * @param url
     * @param params
     * @return
     * @throws Exception
     */
    public static String executePost(String url, Object params, String authorization)  throws  Exception {
        String result = null;
        String setUrl=url;
        String param= JSONObject.toJSONString(params);
        logger.info("请求url:"+url);
        logger.info("请求入参:"+param);
        HttpPost httpPost = new HttpPost(setUrl);
        httpPost.setEntity(new StringEntity(param, ContentType.create("application/json", "utf-8")));
        httpPost.setHeader("Content-Type","application/json");
        if(StringUtils.isNotBlank(authorization)) {
            httpPost.setHeader("Authorization",authorization);
        }
        try {
            HttpResponse response = getHttpClient().execute(httpPost);
            int statusCode = response.getStatusLine().getStatusCode();
            logger.info("statusCode:"+statusCode);
            if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_CREATED || statusCode == HttpStatus.SC_BAD_REQUEST) {
                result = getStreamAsString(response.getEntity().getContent(), "UTF-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new BaseException(500, "网络繁忙, 请稍后再试");
        }
        return result;
    }


    /**
     * 发起请求并返回结果GET
     * @param url
     * @return
     * @throws Exception
     */
    public static String executeGet(String url, String authorization) throws BaseException {
        logger.info("请求url:"+url);
        HttpGet httpGet = new HttpGet(url);

        HttpResponse response = null;
        try {
            httpGet.setHeader("Content-Type",CONTENT_TYPE);
            if(StringUtils.isNotBlank(authorization)) {
                httpGet.setHeader("Authorization",authorization);
            }
            response = getHttpClient().execute(httpGet);
            int statusCode = response.getStatusLine().getStatusCode();
            logger.info("statusCode:"+statusCode);
            if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_CREATED || statusCode == HttpStatus.SC_BAD_REQUEST) {
                return getStreamAsString(response.getEntity().getContent(), "UTF-8");
            } else {
                return null;
            }
        } catch (IOException e) {
            e.printStackTrace();
            throw new BaseException(500, "网络繁忙, 请稍后再试");
        }
    }


    public static String executeGetWithParam(String url, Object param, String authorization){
        JSONObject params = (JSONObject) JSONObject.toJSON(param);
        logger.info("请求地址:{}, 请求参数:{}", url, params.toJSONString());

        StringBuffer paramsStr = new StringBuffer("?");
        String paramResult = null;
        if (!params.isEmpty()) {
            for (Map.Entry<String, Object> entry : params.entrySet()) {
                if (entry.getValue() != null){
                    paramsStr.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
                }
            }
            paramResult = paramsStr.substring(0, paramsStr.length() - 1);
        }

        if (paramResult != null) {
            url = url + paramResult;
        }

        String result = null;
        try {
            result = HttpCommonClientUtils.executeGet(url,authorization);
        } catch (BaseException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 发起请求并返回结果get(body请求体)
     * @param url
     * @return
     * @throws Exception
     */
    public static String executeGethWithBody(String url, Object params, String authorization)  throws  Exception {
        String result = null;
        HttpGetWithBody httpGet = new HttpGetWithBody(url);
        String param= JSONObject.toJSONString(params);
        logger.info("请求url:"+url);
        logger.info("请求入参:"+param);
        httpGet.setEntity(new StringEntity(param, ContentType.create("application/json", "utf-8")));
        httpGet.setHeader("Content-Type",CONTENT_TYPE);
        if(StringUtils.isNotBlank(authorization)) {
            httpGet.setHeader("Authorization",authorization);
        }
        try {
            HttpResponse response = getHttpClient().execute(httpGet);
            int statusCode = response.getStatusLine().getStatusCode();
            logger.info("statusCode:"+statusCode);
            if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_CREATED) {
                result = getStreamAsString(response.getEntity().getContent(), "UTF-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new BaseException(500, "网络繁忙, 请稍后再试");
        }
        return result;
    }

    /**
     * 发起请求并返回结果PUT
     * @param url
     * @param params
     * @return
     * @throws Exception
     */
    public static String executePut(String url, Object params, String authorization)  throws  Exception {
        String result = null;
        String setUrl=url;
        String param= JSONObject.toJSONString(params);
        logger.info("请求url:"+url);
        logger.info("请求入参:"+param);
        HttpPut httpPut = new HttpPut(setUrl);
        httpPut.setEntity(new StringEntity(param,ContentType.create("application/json", "utf-8")));
        httpPut.setHeader("Content-Type",CONTENT_TYPE);
        if(StringUtils.isNotBlank(authorization)) {
            httpPut.setHeader("Authorization",authorization);
        }
        try {
            HttpResponse response = getHttpClient().execute(httpPut);
            int statusCode = response.getStatusLine().getStatusCode();
            logger.info("statusCode:"+statusCode);
            if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_CREATED) {
                result = getStreamAsString(response.getEntity().getContent(), "UTF-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new BaseException(500, "网络繁忙, 请稍后再试");
        }
        return result;
    }


    /**
     * 发起请求并返回结果DELETE
     * @param url
     * @param params
     * @return
     * @throws Exception
     */
    public static String executeDel(String url, Object params, String authorization)  throws  Exception {
        String result = null;
        String setUrl=url;
        String param= JSONObject.toJSONString(params);
        HttpDelete httpdelete = new HttpDelete(setUrl);
        httpdelete.setHeader("Content-Type",CONTENT_TYPE);
        if(StringUtils.isNotBlank(authorization)) {
            httpdelete.setHeader("Authorization",authorization);
        }
        try {
            HttpResponse response = getHttpClient().execute(httpdelete);
            int statusCode = response.getStatusLine().getStatusCode();
            logger.info("statusCode:"+statusCode);
            if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_CREATED) {
                result = getStreamAsString(response.getEntity().getContent(), "UTF-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new BaseException(500, "网络繁忙, 请稍后再试");
        }
        return result;
    }

    /**
     * 发起请求并返回结果DELETE(body请求体)
     * @param url
     * @param params
     * @return
     * @throws Exception
     */
    public static String executeDelWithBody(String url, Object params, String authorization)  throws  Exception {
        String result = null;
        String setUrl=url;
        String param= JSONObject.toJSONString(params);
        HttpDeleteWithBody httpdelete = new HttpDeleteWithBody(setUrl);
        httpdelete.setEntity(new StringEntity(param,ContentType.create("application/json", "utf-8")));
        httpdelete.setHeader("Content-Type",CONTENT_TYPE);
        if(StringUtils.isNotBlank(authorization)) {
            httpdelete.setHeader("Authorization",authorization);
        }
        try {
            HttpResponse response = getHttpClient().execute(httpdelete);
            int statusCode = response.getStatusLine().getStatusCode();
            logger.info("statusCode:"+statusCode);
            if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_CREATED) {
                result = getStreamAsString(response.getEntity().getContent(), "UTF-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new BaseException(500, "网络繁忙, 请稍后再试");
        }
        return result;
    }

    /**
     * 发起请求并返回结果PATCH
     * @param url
     * @param params
     * @return
     * @throws Exception
     */
    public static String executePatch(String url, Object params, String authorization)  throws  Exception {
        String result = null;
        String setUrl=url;
        String param= JSONObject.toJSONString(params);
        HttpPatch httpPatch = new HttpPatch(setUrl);
        httpPatch.setEntity(new StringEntity(param,ContentType.create("application/json", "utf-8")));
        httpPatch.setHeader("Content-Type",CONTENT_TYPE);
        if(StringUtils.isNotBlank(authorization)) {
            httpPatch.setHeader("Authorization",authorization);
        }
        try {
            HttpResponse response = getHttpClient().execute(httpPatch);
            int statusCode = response.getStatusLine().getStatusCode();
            logger.info("statusCode:"+statusCode);
            if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_CREATED) {
                result = getStreamAsString(response.getEntity().getContent(), "UTF-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new BaseException(500, "网络繁忙, 请稍后再试");
        }
        return result;
    }

    /**
     * 将流转换为字符串
     * @param stream
     * @param charset
     * @return
     * @throws IOException
     */
    private static String getStreamAsString(InputStream stream, String charset) throws IOException {
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(stream, charset), 8192);
            StringWriter writer = new StringWriter();

            char[] chars = new char[8192];
            int count = 0;
            while ((count = reader.read(chars)) > 0) {
                writer.write(chars, 0, count);
            }

            return writer.toString();
        } finally {
            if (stream != null) {
                stream.close();
            }
        }
    }

    /**
     *
     * @param requestParam
     * @param coder
     * @return
     */
    private static String getRequestParamString(Map<String, String> requestParam, String coder) {
        if (null == coder || "".equals(coder)) {
            coder = "UTF-8";
        }
        StringBuffer sf = new StringBuffer("");
        String reqstr = "";
        if (null != requestParam && 0 != requestParam.size()) {
            for (Map.Entry<String, String> en : requestParam.entrySet()) {
                try {
                    sf.append(en.getKey()
                            + "="
                            + (null == en.getValue() || "".equals(en.getValue()) ? "" : URLEncoder
                            .encode(en.getValue(), coder)) + "&");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                    return "";
                }
            }
            reqstr = sf.substring(0, sf.length() - 1);
        }
        return reqstr;
    }
}

 

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/weixin_38373006/article/details/105097343

智能推荐

程序员公开上班摸鱼神器!有了它,老板都不好意思打扰你!-程序员宅基地

文章浏览阅读201次。开发者(KaiFaX)面向全栈工程师的开发者专注于前端、Java/Python/Go/PHP的技术社区来源:开源最前线链接:https://github.com/svenstaro/gen..._程序员怎么上班摸鱼

Vue显示和隐藏如何用动画形式显示_显示隐藏从上向下动画效果css vue-程序员宅基地

文章浏览阅读4.9k次。Vue提供了transition的组件,在正常情况中,可以给任何元素和组件添加”进入”和”离开”过渡动画。在使用v-if或者v-show的时候,想让效果好看一些,毕竟前端吗,要审美哈哈~其实好多种实现方法,这里列出这一两种1.使用transition +css实现<div id="app"> <input type="button" value="按钮" @click="toggle"> <transition name="fade"&_显示隐藏从上向下动画效果css vue

怎么重置imac_[Mac硬件]如何重置 Mac 的 SMC-程序员宅基地

文章浏览阅读2k次。本次教程将告诉大家如何重置 Mac 电脑上的 SMC(系统管理控制器),以下教程均针对使用 X86 架构Intel 处理器的 Mac(2005 年 6 月之后生产),早期使用RISC 架构 PowerPC 处理器的 Mac 不适用本教程。Apple SMC 工作原理图一、什么是 SMCSMC 是 System Management Control的缩写,中文名称为系统管理控制器。它是 Mac 主...

宽带的上行跟下行是什么_adsl上下行对称方式-程序员宅基地

文章浏览阅读1.3k次。运营商所说的几M的宽带和下载速度是2个不同的概念。而运营商的几M的宽带,单位是比特(bit),就是说10M宽带实际上是指10M的bit,也是10*1024K的bit。比如现在一般电信的100M家用光纤,上行速度就是12.5M,当然这个M数不是实际的速度,简单可以除以10,就是实际速度,也就是说100M光纤,理论你下载速度可以达到10M每秒,上传则只有1.25M。1、上行速度是你上传的速度,比如你发邮件,上传照片等,下行速度主要是你下载的速度,比如你看电影,下载东西等,平时我们说的几M,都是指下行的速度。_adsl上下行对称方式

kali-进行抓包以及aircrack-ng跑包和hashcat跑包_kali进行抓包-程序员宅基地

文章浏览阅读3.8k次,点赞39次,收藏37次。使用kali进行抓包以及aircrack-ng跑包和hashcat跑包_kali进行抓包

代码版本管理工具介绍_visual source safe 和 svn-程序员宅基地

文章浏览阅读5.9k次。笔者有幸接触过以下几种常用的配置管理工具:VSS、SVN、Clearcase,在此做一个小小的总结,并Ctrl+C了以前一些网友的对比评论,不一定准确,只是希望通过这些总结对自己和初学者有所帮助。如果想进一步了解这些工具,请baidu和google,如果想深入了解,敬请到图书馆借书并实践。一、 Visual Source Safe( 简称 VSS )VSS是微软的产品,是配置管理的一种很好的入门级..._visual source safe 和 svn

随便推点

基于深度学习的股票预测(完整版,有代码)_基于深度学习的股票操纵识别研究python代码-程序员宅基地

文章浏览阅读1.3w次,点赞18次,收藏291次。基于深度学习的股票预测数据获取数据转换LSTM模型搭建训练模型预测结果数据获取采用tushare的数据接口(不知道tushare的筒子们自行百度一下,简而言之其免费提供各类金融数据 , 助力智能投资与创新型投资。)python可以直接使用pip安装tushare!pip install tushareCollecting tushare Downloading https://files.pythonhosted.org/packages/17/76/dc6784a1c07ec040e74_基于深度学习的股票操纵识别研究python代码

中科网威工业级防火墙通过电力行业测评_电力行业防火墙有哪些-程序员宅基地

文章浏览阅读2k次。【IT168 厂商动态】 近日,北京中科网威(NETPOWER)工业级防火墙通过了中国电力工业电力设备及仪表质量检验测试中心(厂站自动化及远动)测试,并成为中国首家通过电力协议访问控制专业测评的工业级防火墙生产厂商。   北京中科网威(NETPOWER)工业级防火墙专为工业及恶劣环境下的网络安全需求而设计,它采用了非X86的高可靠嵌入式处理器并采用无风扇设计,整机功耗不到22W,具备极_电力行业防火墙有哪些

第十三周 ——项目二 “二叉树排序树中查找的路径”-程序员宅基地

文章浏览阅读206次。/*烟台大学计算机学院 作者:董玉祥 完成日期: 2017 12 3 问题描述:二叉树排序树中查找的路径 */#include #include #define MaxSize 100typedef int KeyType; //定义关键字类型typedef char InfoType;typedef struct node

C语言基础 -- scanf函数的返回值及其应用_c语言ignoring return value-程序员宅基地

文章浏览阅读775次。当时老师一定会告诉你,这个一个"warning"的报警,可以不用管它,也确实如此。不过,这条报警信息我们至少可以知道一点,就是scanf函数调用完之后是有一个返回值的,下面我们就要对scanf返回值进行详细的讨论。并给出在编程时利用scanf的返回值可以实现的一些功能。_c语言ignoring return value

数字医疗时代的数据安全如何保障?_数字医疗服务保障方案-程序员宅基地

文章浏览阅读9.6k次。十四五规划下,数据安全成为国家、社会发展面临的重要议题,《数据安全法》《个人信息保护法》《关键信息基础设施安全保护条例》已陆续施行。如何做好“数据安全建设”是数字时代的必答题。_数字医疗服务保障方案

确定性随机数发生器测试向量——DRBG-HMAC-SHA1_drbg_nopr_hmac_sha1-程序员宅基地

文章浏览阅读3.4w次。结构体定义//DRBG测试中用, 因测试使用数据有很多相同之处typedef struct dat_st{ int len; char * dat;}tvstr;//DRBG的测试向量typedef struct drbg_test_vector_st { char * inf; //测试向量的附加信息说明 int alg..._drbg_nopr_hmac_sha1

推荐文章

热门文章

相关标签