依赖 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. 2017-10-15 NOIP模拟赛

    Stack #include<iostream> #include<cstdio> #define mod 7 using namespace std; ][],n; int ...

  2. CF987A Infinity Gauntlet 模拟

    You took a peek on Thanos wearing Infinity Gauntlet. In the Gauntlet there is a place for six Infini ...

  3. Meissel Lehmer Algorithm 求前n个数中素数个数 【模板】

    Count primes Time Limit: 12000/6000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others)Tot ...

  4. JS实现拖拽功能

    本文代码地址(第一节):https://github.com/dirstart/js-exam/blob/master/%E6%8B%96%E6%8B%BDdiv1.html 第二节:https:// ...

  5. BZOJ 4165 矩阵 堆

    先把每个长为$mina$,宽为$minb$的矩阵扔到堆里,然后由于矩阵中的数都是正的,所以我们每取出来一个矩形,,就把他向四个方向扩张一行,再把这新的且更大的四个矩形扔到堆里.注意判重,于是我比较懒用 ...

  6. Base64Utils

    package com.yundaex.common.crypto.base64; import java.io.ByteArrayInputStream; import java.io.ByteAr ...

  7. jetty-env.xml

    <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE Configure PUBLIC &quo ...

  8. PHP var_export

    var_export可以将一个数组转为一个字符串 不同于var_dump,var_export并不会输出数据的类型以及字符大小等,只会简单把数组的key跟value拼接成一个字符串 <?php ...

  9. jquery——尺寸

    1. 获取和设置元素的尺寸 2. 获取元素相对页面的绝对位置:offset() 这种方式增加的盒子不会对之前的结构产生影响 demo: <!DOCTYPE html> <html l ...

  10. 转 Mindoc搭建流程 文档多人编辑工具。

    安装方法参考: https://www.yuanmas.com/info/1bz9Y126zx.html https://www.iminho.me/version.html #step 1,安装My ...