前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >专栏 >封装httpClient工具类进行get、post、put、delete的http接口请求,可添加请求头与参数,支持多线程

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

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

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

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

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
        <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
运行
AI代码解释
复制
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 删除。

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

评论
登录后参与评论
暂无评论
推荐阅读
编辑精选文章
换一批
HTTP 请求工具类
坐标 <dependency> <groupId>net.sf.json-lib</groupId> <artifactId>json-lib</artifactId> <version>2.1</version> <classifier>jdk15</classifier> </dependency> 工具类 package com.baomidou.springboot.uti
高大北
2022/06/14
9300
http请求工具类 HttpClient4Util
1、依赖 <!-- httpclient --> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.3.6</version> </dependency> 2、HttpClient4Util http请求工具类 点击查看代码 import lombok.extern.slf4j.Slf4j; import org.apach
化羽羽
2022/11/12
5200
面试被问:HTTP客户端连接,选择HttpClient还是OkHttp?
这又触及到我的知识盲区了,首先来一波面向百度学习,直接根据关键字httpclient和okhttp的区别、性能比较进行搜索,没有找到想要的答案,于是就去overstackflow上看看是不是有人问过这个问题,果然不会让你失望的
田维常
2020/02/24
10.1K0
Java发送Http请求(HttpClient)
HttpClient 是Apache HttpComponents 下的子项目,用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议。HTTP 协议可能是现在 Internet 上使用得最多、最重要的协议了,越来越多的 Java 应用程序需要直接通过 HTTP 协议来访问网络资源。虽然在 JDK 的 java net包中已经提供了访问 HTTP 协议的基本功能,但是对于大部分应用程序来说,JDK 库本身提供的功能还不够丰富和灵活。HttpClient 是Apache HttpComponents 下的子项目,用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议。
ha_lydms
2023/08/09
1K0
JavaUtil_06_HttpUtil_使用httpclient实现
一、简介 使用 appache 的 httpclient 来实现的 二、源码 package com.ray.weixin.gz.util; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import org.apache.http.Consts; import org.apache.http.Header; import org.
shirayner
2018/08/10
9290
java使用httpclient调用第三方接口
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/141981.html原文链接:https://javaforall.cn
全栈程序员站长
2022/09/01
9080
HttpClient-Json格式、设置超时
Json格式、设置超时 目录 1、Json格式 2、设置超时 1、Json格式 1、创建Json类。 发送数据将数据类型转为Json格式。 接收数据将数据类型转为Json格式。 脚本代码: package com.test.demo; import java.io.IOException; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.CloseableHtt
wangmcn
2022/07/25
6020
HttpClient-Json格式、设置超时
HttpDelete携带json参数(body)的方法
我们使用 Httpclient 时常用的请求有2个,HttpPost 和 HttpGet,一般 HttpPost 对传参 Json 的处理是:
Li_XiaoJin
2022/06/10
2.7K0
HttpDelete携带json参数(body)的方法
HttpClient-Get请求、Post请求
有参数,请求链接为url(http://localhost:8083/getdemo2)
wangmcn
2022/07/25
2.7K0
HttpClient-Get请求、Post请求
HttpClient使用不当,服务挂了,是时候系统学习一下了
事件一:联调微信支付接口,用到HttpClient,花时间整理了一番。如果有一篇文章,读一读就可以掌握HttpClient 80%的内容,再有可以直接用的Demo,下次再遇到是不是就可以非常容易集成了?这篇便是这篇文章的目标之一。
程序新视界
2021/12/20
1.7K0
HttpClient-Header、Cookie
内容格式设定为Json格式("content-type", "application/json")、自定义Header("Self-Header", "MySelfHeader")。
wangmcn
2022/07/25
6440
HttpClient-Header、Cookie
httpclient模拟post请求json封装表单数据
以下代码包括最基本的GET、POST、JSON参数的POST方式的请求。(相当于POSTMAN中使用raw编写的参数)
I Teach You 我教你
2018/12/14
8.2K0
HttpClient在HTTP协议接口测试中的使用
TTP协议的接口测试中,使用到最多的就是GET请求与POST请求,其中POST请求有FORM参数提交请求与RAW请求,下面我将结合HttpClient来实现一下这三种形式:
流柯
2018/08/30
1.9K0
【HttpClientUtil完整的工具类】
package com.test.test.utils; import java.io.IOException; import java.net.URI; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.apache.commons.httpclient.HttpStatus; import org.apache.http.NameValuePair; import org.apa
用户5640963
2019/07/25
9.2K0
java发送请求网络请求
import com.alibaba.fastjson.JSONObject; import lombok.extern.slf4j.Slf4j; import org.apache.http.HttpEntity; import org.apache.http.HttpStatus; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.CloseableHttpResponse
jaychou
2022/12/26
1.8K0
HttpClient详细解释
Http协议的重要性相信不用我多说了,HttpClient相比传统JDK自带的URLConnection,增加了易用性和灵活性(具体区别,日后我们再讨论),它不仅是客户端发送Http请求变得容易,而且也方便了开发人员测试接口(基于Http协议的),即提高了开发的效率,也方便提高代码的健壮性。因此熟练掌握HttpClient是很重要的必修内容,掌握HttpClient后,相信对于Http协议的了解会更加深入。
全栈程序员站长
2022/11/16
1.5K0
Apache httpClient+Jackson学习笔记
HTMLUnit可以用来做爬虫的。Jsoup比他跟简洁。使用python语言进行爬虫.开箱即用。
全栈程序员站长
2022/06/30
2.4K0
Apache httpClient+Jackson学习笔记
HTTP、RPC、UI、SQL自动化封装示例(JAVA)
以下是基于java,分别通过HttpClient、Dubbo、Selenium、JdbcTemplate实现Http、RPC、UI、SQL操作的示例代码。导入依赖包后可直接复制代码执行。
骆小生
2023/03/29
2K0
java中的HttpClient工具类:用于不同系统中接口之间的发送和接收数据
不同系统中接口之间的发送和接收数据:这个需求可以使用Httpclient这种方法进行调用,下边这个工具类包含了get和post两种方法,post发送的是json格式的字符串,get获得的是String字符串,可以使用json解析成 json格式的字符串
知识浅谈
2021/05/10
2K0
基于rest风格对Neo4j进行调用访问之———httpClient
1.什么是rest风格 不知道戳这里 2.什么是Neo4j 简单来说是一个图形数据库,是一种NOSQL型的。具体摸我 3.httpclient 访问 参考官网链接摸我。 代码如下: package neo4j.action; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import neo4j.config.RestTemplateConfiguration; import org.apach
MickyInvQ
2020/09/27
9410
基于rest风格对Neo4j进行调用访问之———httpClient
相关推荐
HTTP 请求工具类
更多 >
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
查看详情【社区公告】 技术创作特训营有奖征文