依赖 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)的更多相关文章

  1. Java 发送 Http请求工具类

    HttpClient.java package util; import java.io.BufferedReader; import java.io.IOException; import java ...

  2. 微信https请求工具类

    工作中用到的微信https请求工具类. package com.gxgrh.wechat.tools; import com.gxgrh.wechat.wechatapi.service.System ...

  3. Http、Https请求工具类

    最近在做微信开发,使用http调用第三方服务API,有些是需要https协议,通过资料和自己编码,写了个支持http和https的工具类,经验证可用,现贴出来保留,也供需要的人使用(有不足的地方,也请 ...

  4. 我的Android进阶之旅------>Android关于HttpsURLConnection一个忽略Https证书是否正确的Https请求工具类

    下面是一个Android HttpsURLConnection忽略Https证书是否正确的Https请求工具类,不需要验证服务器端证书是否正确,也不需要验证服务器证书中的域名是否有效. (PS:建议下 ...

  5. Java发送HTTPS请求

    前言 上篇文章介绍了 java 发送 http 请求,大家都知道发送http是不安全的 .我也是由于对接了其他企业后总结了一套发送 https的工具.大家网上找方法很多的,但是可不是你粘过来就能用啊, ...

  6. HttpClient发起Http/Https请求工具类

    <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpcl ...

  7. Java模仿http请求工具类

    package ln; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamRea ...

  8. 接口使用Http发送post请求工具类

    HttpClientKit import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamR ...

  9. Java 实现 Http 请求工具类

    package com.demo.util; import java.io.BufferedReader; import java.io.IOException; import java.io.Inp ...

随机推荐

  1. EOS多主机多节点环境配置

    本文使用了四台同网段的主机,第一台做为eosio创世用户使用,另外三台做为出块者节点使用,最终实现了EOS多主机多节点的配置.最后EOSIO创世用户不再出块,由选举出来的各个节点轮流出块,下面将介绍具 ...

  2. [USACO07DEC]观光奶牛Sightseeing Cows 二分答案+判断负环

    题目描述 Farmer John has decided to reward his cows for their hard work by taking them on a tour of the ...

  3. JMeter - REST API测试 - 完整的数据驱动方法(翻译)

    https://github.com/vinsguru/jmeter-rest-data-drivern/tree/master 在本文中,我想向您展示一种用于REST API测试的数据驱动方法.如果 ...

  4. js怎样实现继承

    js实现继承的5种方式 js是门灵活的语言,实现一种功能往往有多种做法,ECMAScript没有明确的继承机制,而是通过模仿实现的,根据js语言的本身的特性,js实现继承有以下通用的几种方式1.使用对 ...

  5. Eclipse(2019-03版本)汉化

    1.Eclipse IDE 版本 eclipse-jee-2019-03-R-win32-x86_64.zip 2.Eclipse 汉化包下载 babel-R0.16.0-photon.zip 3.解 ...

  6. 【ACM】拦截导弹 - 0-1背包问题

    拦截导弹 时间限制:3000 ms  |  内存限制:65535 KB 难度:3   描述 某国为了防御敌国的导弹袭击,发展中一种导弹拦截系统.但是这种导弹拦截系统有一个缺陷:虽然它的第一发炮弹能够到 ...

  7. docker~aspnetcore2.0镜像安装软件的加速器

    一般对于安装软件加速时,我们大多数会选择阿里云,而对于aspnetcore2.0这个进项来说,由于使用的是Debian操作系统,所有我们要找到它对应的mirror列表,下面是我整理的一个sources ...

  8. Axure7.0注册码 Axure7.0序列号 Axure7.0License key

    很多同学安装了Axure7.0,但找不到注册码(license key).以前网上流传的Axure6.5的注册码不能用了.下面整理几个可用的Axure7.0注册码分享给大家,祝大家使用愉快,做出更多牛 ...

  9. idea代码生成功能 live template

    一 界面 二 添加 三 编写模板 模板可以通过看其他的模板学习相应语法,难不倒程序员的 四 选择适应范围 五 本人常用的模板 log private static final Logger log = ...

  10. C#数据库(MSSQL)帮助类

    /// <summary> /// 数据库帮助类 /// <author>Devin</author> /// </summary> public se ...