HttpUtil工具类,发送Get/Post请求,支持Http和Https协议
HttpUtil工具类,发送Get/Post请求,支持Http和Https协议
使用用Httpclient封装的HttpUtil工具类,发送Get/Post请求
1. maven引入httpclient依赖
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.12</version>
</dependency>
2. GET请求
public static String doGet(String path, Map<String, String> param, Map<String, String> headers) {
HttpGet httpGet = null;
CloseableHttpResponse response = null;
CloseableHttpClient httpClient = wrapClient(path);
// 创建uri
URIBuilder builder = null;
try {
builder = new URIBuilder(path);
if (param != null) {
for (String key : param.keySet()) {
builder.addParameter(key, param.get(key));
}
}
URI uri = builder.build();
// 创建http GET请求
httpGet = new HttpGet(uri);
if (headers != null && headers.size() > 0) {
for (Map.Entry<String, String> entry : headers.entrySet()) {
httpGet.addHeader(entry.getKey(), entry.getValue());
}
}
// 执行请求
response = httpClient.execute(httpGet);
// 判断返回状态是否为200
if (response.getStatusLine().getStatusCode() == 200) {
return EntityUtils.toString(response.getEntity(), "UTF-8");
}
} catch (Exception e) {
throw new RuntimeException("[发送Get请求错误:]" + e.getMessage());
} finally {
try {
httpGet.releaseConnection();
response.close();
if (httpClient != null) {
httpClient.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
3. POST请求
public static String doPostJson(String url, String jsonParam, Map<String, String> headers) {
HttpPost httpPost = null;
CloseableHttpResponse response = null;
CloseableHttpClient httpClient = wrapClient(url);
try {
httpPost = new HttpPost(url);
//addHeader,如果Header没有定义则添加,已定义则不变,setHeader会重新赋值
httpPost.addHeader("Content-type","application/json;charset=utf-8");
httpPost.setHeader("Accept", "application/json");
StringEntity entity = new StringEntity(jsonParam, StandardCharsets.UTF_8);
// entity.setContentType("text/json");
// entity.setContentEncoding(new BasicHeader("Content-Type", "application/json;charset=UTF-8"));
httpPost.setEntity(entity);
//是否有header
if (headers != null && headers.size() > 0) {
for (Map.Entry<String, String> entry : headers.entrySet()) {
httpPost.addHeader(entry.getKey(), entry.getValue());
}
}
// 执行请求
response = httpClient.execute(httpPost);
// 判断返回状态是否为200
if (response.getStatusLine().getStatusCode() == 200) {
return EntityUtils.toString(response.getEntity(), "UTF-8");
}
} catch (Exception e) {
throw new RuntimeException("[发送POST请求错误:]" + e.getMessage());
} finally {
try {
httpPost.releaseConnection();
response.close();
if (httpClient != null) {
httpClient.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
3. 获取httpclient的方法
这里会根据url自动匹配需要的是http的还是https的client
private static CloseableHttpClient wrapClient(String url) {
CloseableHttpClient client = HttpClientBuilder.create().build();
if (url.startsWith("https")) {
client = getCloseableHttpsClients();
}
return client;
}
4. 对于https的需要自己实现一下client
private static CloseableHttpClient getCloseableHttpsClients() {
// 采用绕过验证的方式处理https请求
SSLContext sslcontext = createIgnoreVerifySSL();
// 设置协议http和https对应的处理socket链接工厂的对象
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.INSTANCE)
.register("https", new SSLConnectionSocketFactory(sslcontext)).build();
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
HttpClients.custom().setConnectionManager(connManager);
// 创建自定义的httpsclient对象
CloseableHttpClient client = HttpClients.custom().setConnectionManager(connManager).build();
return client;
}
private static SSLContext createIgnoreVerifySSL() {
// 创建套接字对象
SSLContext sslContext = null;
try {
//指定TLS版本
sslContext = SSLContext.getInstance("TLSv1.2");
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("[创建套接字失败:] " + e.getMessage());
}
// 实现X509TrustManager接口,用于绕过验证
X509TrustManager trustManager = new X509TrustManager() {
@Override
public void checkClientTrusted(java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
String paramString) throws CertificateException {
}
@Override
public void checkServerTrusted(java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
String paramString) throws CertificateException {
}
@Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
};
try {
//初始化sslContext对象
sslContext.init(null, new TrustManager[]{trustManager}, null);
} catch (KeyManagementException e) {
throw new RuntimeException("[初始化套接字失败:] " + e.getMessage());
}
return sslContext;
}
以上全部都测试通过,如果有错误,欢迎大佬们指出,感谢!!!
备注:完整版的点这里
让坚持成为品质,让优秀成为习惯!加油!
HttpUtil工具类,发送Get/Post请求,支持Http和Https协议的更多相关文章
- HttpUtil工具类
HttpUtil工具类 /** * 向指定URL发送GET方法的请求 * * @param url * 发送请求的URL * @param params * 请求参数,请求参数应该是name1=val ...
- 牛客网Java刷题知识点之UDP协议是否支持HTTP和HTTPS协议?为什么?TCP协议支持吗?
不多说,直接上干货! 福利 => 每天都推送 欢迎大家,关注微信扫码并加入我的4个微信公众号: 大数据躺过的坑 Java从入门到架构师 人工智能躺过的坑 ...
- Spring Boot项目如何同时支持HTTP和HTTPS协议
如今,企业级应用程序的常见场景是同时支持HTTP和HTTPS两种协议,这篇文章考虑如何让Spring Boot应用程序同时支持HTTP和HTTPS两种协议. 准备 为了使用HTTPS连接器,需要生成一 ...
- 通过Httpclient工具类,实现接口请求
package luckyweb.seagull.util; import org.apache.http.NameValuePair; import org.apache.http.client.e ...
- httpclient4.5.2 Post请求支持http和https
先导入所需的jar包,pom.xml <dependency> <groupId>org.springframework.boot</groupId> <ar ...
- 工具类: 用于模拟HTTP请求中GET/POST方式
package com.jarvis.base.util; import java.io.BufferedReader; import java.io.IOException; import java ...
- 工具类总结---(六)---之http及https请求
下面使用的是HttpURLConnection进行的网络链接,并对https进行了忽略证书. 在这个utils里面,也使用到前面几个utils,比如下载文件的方法,就使用到了Fileutils pac ...
- 自己写的Android端HttpUtil工具类
package com.sxt.jcjd.util; import java.io.IOException; import java.io.UnsupportedEncodingException; ...
- HttpClientUtil 工具类 实现跨域请求数据
package com.xxx.common.util; import java.io.IOException; import java.net.URI; import java.util.Array ...
随机推荐
- 轻松扩展机器学习能力:如何在Rancher上安装Kubeflow
随着机器学习领域不断发展,对于处理机器学习的团队来说,在1台机器上训练1个模型已经有些难以为继,并且现在业界的共识是机器学习已经不仅仅是简单的模型训练. 在模型训练之前.过程中和之后,需要进行许多活动 ...
- NodeJS的概述
1.NodeJS概述 基于谷歌V8引擎,运行在服务器端的环境 对比JS和NodeJS (1)JS运行在浏览器端,存在多种浏览器解释器,容易产生兼容性的问题:而NodeJS运行在服务器端,只有V8引擎一 ...
- 情人节闷在家里做画( 安卓统计图MPAndroidChart开发 )
有些时候觉得一个人挺好的,可以更自由安排自己的时间: 有些时候觉得有个人挺好的,很多事情一个人做起来太没意思了,纵使心中澎湃,倾听的独有自己. 废话少说,直接上图 MPAndroidChart是啥 一 ...
- Ubuntu下配置Hyperledger Fabric环境
在win10系统的台式机上安装配置Hyperledger Fabric环境 安装Ubuntu 16.04 双系统 镜像下载地址:https://www.ubuntu.com/download/desk ...
- Java——删除Map集合中key-value值
通过迭代器删除Map集合中的key-value值 Iterator<String> iter = map.keySet().iterator(); while(iter.hasNext() ...
- 基本sql语法
SQL 语句主要可以划分为以下 3 个类别. DDL(Data Definition Languages)语句:数据定义语言,这些语句定义了不同的数据段.数据库.表.列.索引等数据库对象的定义.常用 ...
- Javascript输入输出语句
方法 说明 归属 alert(msg) 浏览器弹出警示框 浏览器 console.log(msg) 浏览器控制台打印输出信息 浏览器 prompt(info) 浏览器弹出输入框,用户可以输入 浏览器 ...
- 3.CSS字体属性
CSS Fonts(字体)属性用定义字体系列,大小粗细,和文字样式(如斜体) 3.1字体系列 CSS使用font-family属性定义文本字体系列 p { font-family:'微软雅黑' ;} ...
- Hive 集成 Hudi 实践(含代码)| 可能是全网最详细的数据湖系列
公众号后台越来越多人问关于数据湖相关的内容,看来大家对新技术还是很感兴趣的.关于数据湖的资料网络上还是比较少的,特别是实践系列,对于新技术来说,基础的入门文档还是很有必要的,所以这一篇希望能够帮助到想 ...
- Rocket - diplomacy - MixedNode
https://mp.weixin.qq.com/s/zgeAI2n-2cHJi7-Ra5rYZA 介绍MixedNode的实现. 1. 类定义 2. inner/ou ...