依赖 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. msyql分区与分库分表

    分区 工作原理 对用户而言,分区表是一个独立的逻辑表,但是底层MySQL将其分成多个物理子表,这对用户来说是透明的,每一个分区表都会使用一个独立的表文件. 如果数据量比较大,可以进行分区.分区对PHP ...

  2. C#正则表达式快速入门

    作者将自己在学习正则表达式中的心得和笔记作了个总结性文章,希望对初学C#正则表达式的读者有帮助. [内容] 什么是正则表达式 涉及的基本的类 正则表达式基础知识 构建表达式基本方法 编写一个检验程序 ...

  3. 让你的IDEA倍爽

    使用IDEA开发有 一段时间了,从陌生到熟悉的过程算是很平稳的度过,感谢IntelliJ IDEA交流群(群号244908708)里面的群友对我提供的帮助,感谢群主的github上面提供的资料. 这篇 ...

  4. springBoot2.0 配置 mybatis+mybatisPlus+redis

    一.Idea新建springBoot项目 next到完成,然后修改使用自己的maven 等待下载包 二.pom.xml文件 <?xml version="1.0" encod ...

  5. 简单使用phpspider采集本博客文章内容

    采集流程 根据链接获取页面内容(curl)->获取需要采集的内容(可以通过正则.xpath.css选择器等方法进行筛选) <?php require_once 'phpspider/aut ...

  6. Jmeter report优化

    优化大致过程 生成并的报告模板: <?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet ...

  7. 不要忽视Web编程中的小细节

    概述:长时间以来,我们创造了某些在构造和范围内用以提升网站易用性的约定和实践.然后在我们进行web编程的时候总有一些疏忽和纰漏.这里总结了一些web编程时容易出现的小错误,并给出了相应的补救方法,希望 ...

  8. 2017 ACM/ICPC Asia Regional Shenyang Online number number number

    题意:求n个斐波那契数列组合都无法得到的最小数字 解法: 1 我们先暴力的求出前面几个数字 2 然后再暴力的求递推 3 接着矩阵快速幂(没写错吧?) /*#include<bits/stdc++ ...

  9. python大战机器学习——模型评估、选择与验证

    1.损失函数和风险函数 (1)损失函数:常见的有 0-1损失函数  绝对损失函数  平方损失函数  对数损失函数 (2)风险函数:损失函数的期望      经验风险:模型在数据集T上的平均损失 根据大 ...

  10. RandomAccesssFileTest

    package com.yd.wmsc.util; import java.io.IOException; import java.io.RandomAccessFile; public class ...