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

封装httpClient工具类进行get、post、put、delete的http接口请求,可添加请求头与参数,支持多线程首先需要json以及springframework的maven依赖:<dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.62</version></dependency>

大家好,又见面了,我是你们的朋友全栈君。如果您正在找激活码,请点击查看最新教程,关注关注公众号 “全栈程序员社区” 获取激活教程,可能之前旧版本教程已经失效.最新Idea2022.1教程亲测有效,一键激活。

Jetbrains全系列IDE使用 1年只要46元 售后保障 童叟无欺

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

        <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以及支持多线程:

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.net/157763.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • 浏览器visibilitychange事件

    浏览器visibilitychange事件1.项目中,从一个页面进入到另一个页面,然后在这个页面做一些修改后返回到第一个页面,这个时候第一个页面没有刷新只类似tab切换,所以用户的修改未生效。使用html的浏览器事件visibilitychange2.此事件已经得到了广泛应用,但是一些老版本的浏览器需要加相应的前缀3.微信内置的浏览器因为没有标签,所以不会触发该事件手机端直接按Home键回到桌面,也不会触发该事…

    2022年6月29日
    32
  • 边缘检测算子Canny原理概述并利用OpenCV的库函数Canny()对图像进行边缘检测[通俗易懂]

    边缘检测算子Canny原理概述并利用OpenCV的库函数Canny()对图像进行边缘检测[通俗易懂]图像边缘检测的概念和大概原理可以参考我的另一篇博文,链接如下:https://blog.csdn.net/wenhao_ir/article/details/51743382本篇博文介绍边缘检测算子Canny,并利用OpenCV的库函数Canny()对图像进行边缘检测。Canny算子是JohnCanny在1986年发表的论文中首次提出的边缘检测算子,该算子检测性能比较好,应用广泛。Canny算法被推崇为当今最优的边缘检测的算法。Canny算子进行边缘检测的原理和步骤如下:⑴消除噪声。边缘

    2022年5月29日
    36
  • [转]软件开发工作量/费用估算

    [转]软件开发工作量/费用估算软件开发工作量/费用估算2018-05-0308:39:20 NOW_wyp软件开发工作量/费用估算2018-05-0308:39:20 NOW_wyp软件开发工作量/

    2022年7月3日
    22
  • vmware安装ubuntu18.04教程(如何在虚拟机安装软件)

    Windows下VM16虚拟机安装Ubuntu20.04下载链接和手把手的详细教程,同时还有更换软件源和命令行安装VMTools实现跨系统复制粘贴教程

    2022年4月14日
    48
  • Java 编译时多态和运行时多态

    Java 编译时多态和运行时多态根据何时确定执行多态方法中的哪一个,多态分为两种情况:编译时多态和运行时多态。如果在编译时能够确定执行多态方法中的哪一个,称为编译时多态,否则称为运行时多态。一、编译时多态    方法重载都是编译时多态。根据实际参数的数据类型、个数和次序,Java在编译时能够确定执行重载方法中的哪一个。    方法覆盖表现出两种多态性,当对象引用本类实例时,为编译时多态,否则

    2022年5月24日
    64
  • ubuntu 微信开发者工具_微信web开发者工具官方下载

    ubuntu 微信开发者工具_微信web开发者工具官方下载下载地址:开发者工具下载解压到/optsudomkdir/opt/wxdt&&sudotar-zxvfwechat-devtools-1.03.2006090.tar.gz-C/opt/wxdtsudoln-s/opt/wxdt/bin/wechat-devtools/usr/bin/wd创建桌面图标文件vim~/.local/share/applications/wedt.desktop写入[DesktopEntry]Encoding=UT

    2022年10月29日
    0

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号