依赖 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. pb_ds的优先队列实现dijkstra

    用pb_ds的优先队列来做dijkstra..据说noip能用哟. 先来篇关于仿函数的文章. 由于pb_ds支持由迭代器访问元素,并且push操作会返回一个迭代器,merge操作会更新迭代器,相当于帮 ...

  2. 2017-10-17 NOIP模拟赛2

    a [问题描述]你是能看到第一题的 friends 呢.——hja何大爷对字符串十分有研究,于是天天出字符串题虐杀 zhx.何大爷今天为字符串定义了新的权值计算方法.一个字符串由小写字母组成,字符串的 ...

  3. JAVA之反射(一)

    反射(一) ** 注:博主的这篇文章是在学习反射的时间写的如有问题请及时联系博主进行修改 ** 何为反射  这里也不说一些很官方的语言了,官方的说明看着头痛,总之一句话,就是在JAVA的运行状态的时候 ...

  4. UVA307 Sticks

    题意:一组等长的木棒,将它们随机的砍掉,得到若干根小木棍, 每一节小棍的长度都不超过50个单位.然后想把这些木棍拼接起来,恢复到裁剪前的状态, 但忘记了初始时有多少木棒以及木棒的初始长度.计算木棒的可 ...

  5. tp5模型事件回调函数中不能使用$this

    tp5模型事件回调函数中不能使用$this,使用会报错,涉及到数据库操作使用Db类,不能使用$this->save()之类的方式 如果回调函数中需要使用类内函数,需要将函数定义为static,通 ...

  6. Java基础笔记(十四)——面向对象(续)【构造方法和this关键字】

    一.构造函数的规则 1.构造方法是用来在对象实例化时初始化对象的成员变量的,以完成对象的初始化工作. 2.构造方法与类名相同且没有返回值(返回值也不能为void型).如:public 构造方法名( ) ...

  7. Exadata中Infiniband交换机升级

    Infiniband交换机的软件补丁包,随着软件版本的不同,其发布方式也有所变化,从如下图表可以看出,1.3.3-2这个版本是一个分水岭,这个版本及以前的版本,补丁包是单独下载的,而之后的版本,inf ...

  8. sqllocaldb 的使用记录

    sql脚本是一个文件大约也就几MB,要是有一种文件存储数据就好了,后来了解到了sqllocaldb,但是没有深入研究大概知道有这么一个东西.这次翻出来还是自家小姑姑要做winfrom但是苦于sqlse ...

  9. Webpack, 现在最流行的模块打包工具.压缩打包

    压缩bundle.js 1.把我们项目的代码从es6 -> es5 [babel] 参考:http://babeljs.io/docs/setup/#installation 1.1.安装包 b ...

  10. Codeforces Round #363 (Div. 2) A

     Description There will be a launch of a new, powerful and unusual collider very soon, which located ...