Java 发送 Https 请求工具类 (兼容http)
依赖 jsoup-1.11.3.jar
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.11.3</version>
</dependency>
HttpUtils.java
package javax.utils; import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry; import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.X509TrustManager; import org.jsoup.Connection;
import org.jsoup.Connection.Method;
import org.jsoup.Connection.Response;
import org.jsoup.Jsoup; /**
* Http发送post请求工具,兼容http和https两种请求类型
*/
public class HttpUtils { /**
* 请求超时时间
*/
private static final int TIME_OUT = 120000; /**
* Https请求
*/
private static final String HTTPS = "https"; /**
* Content-Type
*/
private static final String CONTENT_TYPE = "Content-Type"; /**
* 表单提交方式Content-Type
*/
private static final String FORM_TYPE = "application/x-www-form-urlencoded;charset=UTF-8"; /**
* JSON提交方式Content-Type
*/
private static final String JSON_TYPE = "application/json;charset=UTF-8"; /**
* 发送Get请求
*
* @param url 请求URL
* @return HTTP响应对象
* @throws IOException 程序异常时抛出,由调用者处理
*/
public static Response get(String url) throws IOException {
return get(url, null);
} /**
* 发送Get请求
*
* @param url 请求URL
* @param headers 请求头参数
* @return HTTP响应对象
* @throws IOException 程序异常时抛出,由调用者处理
*/
public static Response get(String url, Map<String, String> headers) throws IOException {
if (null == url || url.isEmpty()) {
throw new RuntimeException("The request URL is blank.");
} // 如果是Https请求
if (url.startsWith(HTTPS)) {
getTrust();
}
Connection connection = Jsoup.connect(url);
connection.method(Method.GET);
connection.timeout(TIME_OUT);
connection.ignoreHttpErrors(true);
connection.ignoreContentType(true);
connection.maxBodySize(0); if (null != headers) {
connection.headers(headers);
} Response response = connection.execute();
return response;
} /**
* 发送JSON格式参数POST请求
*
* @param url 请求路径
* @param params JSON格式请求参数
* @return HTTP响应对象
* @throws IOException 程序异常时抛出,由调用者处理
*/
public static Response post(String url, String params) throws IOException {
return doPostRequest(url, null, params);
} /**
* 发送JSON格式参数POST请求
*
* @param url 请求路径
* @param headers 请求头中设置的参数
* @param params JSON格式请求参数
* @return HTTP响应对象
* @throws IOException 程序异常时抛出,由调用者处理
*/
public static Response post(String url, Map<String, String> headers, String params) throws IOException {
return doPostRequest(url, headers, params);
} /**
* 字符串参数post请求
*
* @param url 请求URL地址
* @param paramMap 请求字符串参数集合
* @return HTTP响应对象
* @throws IOException 程序异常时抛出,由调用者处理
*/
public static Response post(String url, Map<String, String> paramMap) throws IOException {
return doPostRequest(url, null, paramMap, null);
} /**
* 带请求头的普通表单提交方式post请求
*
* @param headers 请求头参数
* @param url 请求URL地址
* @param paramMap 请求字符串参数集合
* @return HTTP响应对象
* @throws IOException 程序异常时抛出,由调用者处理
*/
public static Response post(Map<String, String> headers, String url, Map<String, String> paramMap) throws IOException {
return doPostRequest(url, headers, paramMap, null);
} /**
* 带上传文件的post请求
*
* @param url 请求URL地址
* @param paramMap 请求字符串参数集合
* @param fileMap 请求文件参数集合
* @return HTTP响应对象
* @throws IOException 程序异常时抛出,由调用者处理
*/
public static Response post(String url, Map<String, String> paramMap, Map<String, File> fileMap) throws IOException {
return doPostRequest(url, null, paramMap, fileMap);
} /**
* 带请求头的上传文件post请求
*
* @param url 请求URL地址
* @param headers 请求头参数
* @param paramMap 请求字符串参数集合
* @param fileMap 请求文件参数集合
* @return HTTP响应对象
* @throws IOException 程序异常时抛出,由调用者处理
*/
public static Response post(String url, Map<String, String> headers, Map<String, String> paramMap, Map<String, File> fileMap) throws IOException {
return doPostRequest(url, headers, paramMap, fileMap);
} /**
* 执行post请求
*
* @param url 请求URL地址
* @param headers 请求头
* @param jsonParams 请求JSON格式字符串参数
* @return HTTP响应对象
* @throws IOException 程序异常时抛出,由调用者处理
*/
private static Response doPostRequest(String url, Map<String, String> headers, String jsonParams) throws IOException {
if (null == url || url.isEmpty()) {
throw new RuntimeException("The request URL is blank.");
} // 如果是Https请求
if (url.startsWith(HTTPS)) {
getTrust();
} Connection connection = Jsoup.connect(url);
connection.method(Method.POST);
connection.timeout(TIME_OUT);
connection.ignoreHttpErrors(true);
connection.ignoreContentType(true);
connection.maxBodySize(0); if (null != headers) {
connection.headers(headers);
} connection.header(CONTENT_TYPE, JSON_TYPE);
connection.requestBody(jsonParams); Response response = connection.execute();
return response;
} /**
* 普通表单方式发送POST请求
*
* @param url 请求URL地址
* @param headers 请求头
* @param paramMap 请求字符串参数集合
* @param fileMap 请求文件参数集合
* @return HTTP响应对象
* @throws IOException 程序异常时抛出,由调用者处理
*/
private static Response doPostRequest(String url, Map<String, String> headers, Map<String, String> paramMap, Map<String, File> fileMap) throws IOException {
if (null == url || url.isEmpty()) {
throw new RuntimeException("The request URL is blank.");
} // 如果是Https请求
if (url.startsWith(HTTPS)) {
getTrust();
} Connection connection = Jsoup.connect(url);
connection.method(Method.POST);
connection.timeout(TIME_OUT);
connection.ignoreHttpErrors(true);
connection.ignoreContentType(true);
connection.maxBodySize(0); if (null != headers) {
connection.headers(headers);
} // 收集上传文件输入流,最终全部关闭
List<InputStream> inputStreamList = null;
try { // 添加文件参数
if (null != fileMap && !fileMap.isEmpty()) {
inputStreamList = new ArrayList<InputStream>();
InputStream in = null;
File file = null;
for (Entry<String, File> e : fileMap.entrySet()) {
file = e.getValue();
in = new FileInputStream(file);
inputStreamList.add(in);
connection.data(e.getKey(), file.getName(), in);
}
} // 普通表单提交方式
else {
connection.header(CONTENT_TYPE, FORM_TYPE);
} // 添加字符串类参数
if (null != paramMap && !paramMap.isEmpty()) {
connection.data(paramMap);
} Response response = connection.execute();
return response;
} // 关闭上传文件的输入流
finally {
closeStream(inputStreamList);
}
} /**
* 关流
*
* @param streamList 流集合
*/
private static void closeStream(List<? extends Closeable> streamList) {
if (null != streamList) {
for (Closeable stream : streamList) {
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
} /**
* 获取服务器信任
*/
private static void getTrust() {
try {
HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() { public boolean verify(String hostname, SSLSession session) {
return true;
}
});
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, new X509TrustManager[] { new X509TrustManager() { public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {} public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {} public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
} }, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());
} catch (Exception e) {
e.printStackTrace();
}
} }
.
Java 发送 Https 请求工具类 (兼容http)的更多相关文章
- Java 发送 Http请求工具类
HttpClient.java package util; import java.io.BufferedReader; import java.io.IOException; import java ...
- 微信https请求工具类
工作中用到的微信https请求工具类. package com.gxgrh.wechat.tools; import com.gxgrh.wechat.wechatapi.service.System ...
- Http、Https请求工具类
最近在做微信开发,使用http调用第三方服务API,有些是需要https协议,通过资料和自己编码,写了个支持http和https的工具类,经验证可用,现贴出来保留,也供需要的人使用(有不足的地方,也请 ...
- 我的Android进阶之旅------>Android关于HttpsURLConnection一个忽略Https证书是否正确的Https请求工具类
下面是一个Android HttpsURLConnection忽略Https证书是否正确的Https请求工具类,不需要验证服务器端证书是否正确,也不需要验证服务器证书中的域名是否有效. (PS:建议下 ...
- Java发送HTTPS请求
前言 上篇文章介绍了 java 发送 http 请求,大家都知道发送http是不安全的 .我也是由于对接了其他企业后总结了一套发送 https的工具.大家网上找方法很多的,但是可不是你粘过来就能用啊, ...
- HttpClient发起Http/Https请求工具类
<dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpcl ...
- Java模仿http请求工具类
package ln; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamRea ...
- 接口使用Http发送post请求工具类
HttpClientKit import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamR ...
- Java 实现 Http 请求工具类
package com.demo.util; import java.io.BufferedReader; import java.io.IOException; import java.io.Inp ...
随机推荐
- bzoj4873: [Shoi2017]寿司餐厅(最小割)
传送门 大佬们是怎么一眼看出这是一个最大权闭合子图的……大佬好强->这里 1.把所有区间$(i,j)$看成一个点,如果权值大于0,则从$S$向他连边,容量为权值,否则从它向$T$连边,容量为权值 ...
- 一起来造一个RxJava,揭秘RxJava的实现原理
一类创业者基本都是做传统行业的,这类创业者非常大胆,也非常舍得投入.很多时候他们如果看到或者想到一个商机,就会投入成千上百万,先把产品做出来,然后再去想怎么开拓市场. 这类传统行业的老板,问我最多的问 ...
- 解决Nginx启动失败
一.Nginx下载http://nginx.org/en/download.html 二.Nginx启动失败原因1.本人下载的是nginx-1.12.1(稳定版),下载完解压后,进入路径中,start ...
- [转]深入探讨C语言中局部变量与全局变量的作用域与存储类别
C语言中局部变量和全局变量变量的作用域与存储类别(auto,static,extern,register) 1.局部变量和全局变量在讨论函数的形参变量时曾经提到,形参变量只在被调用期间才分配内存单元, ...
- maven插件: shade, assembly
shade插件的作用: 通过版本的exclution无法解决jar冲突的问题, 解决方案是把依赖的包打到本model的jar中,打包的时候由mvn plugin自动修改代码中的依赖jar包名 relo ...
- JS——操作元素属性
属性的操作包括:读和写 方法: 1)”.“操作 2)”[ ]“操作 eg: var oDiv = document.getElementById('div1'); var attr = 'color' ...
- AJAX (分页)
<!-- 企业新闻列表开始,图尺寸550*310,如果没图,则在li上加on --> <div class="common-box new-box"> &l ...
- Python解析CSV中的多维字典
CSV文件结构如下,其中字段A为唯一 代码如下,Python27 with open(file_obj+'TEST.CSV','r') as f: #转为字典 Reader=csv.DictReade ...
- {ldelim},{rdelim} - smarty 内建函数
{ldelim}和{rdelim}用来转义模板的分隔符,缺省为{和}.你也可以用{literal}{/literal}来转义文本块(如Javascript或CSS). 例: {* 在模板外将原样打印分 ...
- C++中的swap函数
最通用的模板交换函数模式:创建临时对象,调用对象的赋值操作符 template <class T> void swap ( T& a, T& b ) { T c(a); a ...