封装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();
}
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

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

【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛

【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...

(0)


相关推荐

  • python基础语法个人笔记_python基础题库

    python基础语法个人笔记_python基础题库python语法规范python的语法规范非常重要,简洁明了是python的特性,以下是python语法的一些说明python3的编码格式是unicode(utf-8)标识符的规则:由字母、数字

  • postgresql connection refused 5432 win10[通俗易懂]

    postgresql connection refused 5432 win10[通俗易懂]一个小问题困扰了我很久,最后解决了,可是具体问题在哪里我还是没明白。我使用的win10系统,之前eclipsejdbcpostgresql连接完全没有问题,有天发现屏幕下端的搜索框不能使用了,在网上找了解决方法,在powershell上重装了微软小娜,解决了这个搜索框不能使用的问题。可是后来发现eclipse使用jdbc一直连不上postgresql,报错java.net,Conn…

  • 一文认识PYNQ

    零、前言PYNQ可以认为是Python+ZYNQ,但不是简单的相加。在使用上,可以说PYNQ开发是ZYNQ开发的集大成,也可以说PYNQ是ZYNQ的全栈式开发,里面涉及到的内容不仅包括FPGA设计、PS与PL的协同交互、HLS、linux驱动开发,而且还要熟悉Python开发并且使用Python各种库。PYNQ是Xilinx推出的一个开源项目,目的是使用Python开发Xilinx平台更加容易。使用Python语言和库,设计人员可以利用Xilin

  • java cloneable 接口_Cloneable 接口 记号接口(标记接口)「建议收藏」

    java cloneable 接口_Cloneable 接口 记号接口(标记接口)「建议收藏」Cloneable接口指示了一个类提供了一个安全的clone方法。首先了解Object.clone()方法:clone是Object超类的一个protected方法,用户代码不能直接调用这个方法。Object的子类只能调用Object超类中受保护的clone方法来克隆它自己的对象,必须重新定义clone为public才能允许所有方法调用这个类的实例的clone方法克隆对象。clone方法的作用:…

  • Redis实战之Redis命令

    Redis可以存储键与5种不同数据结构类型之间的映射,这5种数据结构类型分别为string(字符串),list(列表),set(集合),hash(散列),zset(有序集合),下面将分别对这5种数据类

    2021年12月29日
  • vue上传文件流

    vue上传文件流创建formData方法,把文件流以及所有需要上传的数据通过formData.append传入formData中,上传请求中的data中只需要放一个formData就可以了。(此处request为封装的请求方法,省事可以不封装)

    2022年10月16日

发表回复

您的电子邮箱地址不会被公开。

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