packagejavax.utils;importjava.io.Closeable;importjava.io.File;importjava.io.FileInputStream;importjava.io.IOException;importjava.io.InputStream;importjava.security.SecureRandom;importjava.security.cert.CertificateException;importjava.security.cert.X509Certificate;importjava.util.ArrayList;importjava.util.List;importjava.util.Map;importjava.util.Map.Entry;importjavax.net.ssl.HostnameVerifier;importjavax.net.ssl.HttpsURLConnection;importjavax.net.ssl.SSLContext;importjavax.net.ssl.SSLSession;importjavax.net.ssl.X509TrustManager;importorg.jsoup.Connection;importorg.jsoup.Connection.Method;importorg.jsoup.Connection.Response;importorg.jsoup.Jsoup;/*** Http发送post请求工具,兼容http和https两种请求类型*/
public classHttpUtils {/*** 请求超时时间*/
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请求
*
*@paramurl 请求URL
*@returnHTTP响应对象
*@throwsIOException 程序异常时抛出,由调用者处理*/
public static Response get(String url) throwsIOException {return get(url, null);
}/*** 发送Get请求
*
*@paramurl 请求URL
*@paramheaders 请求头参数
*@returnHTTP响应对象
*@throwsIOException 程序异常时抛出,由调用者处理*/
public static Response get(String url, Map headers) throwsIOException {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();returnresponse;
}/*** 发送JSON格式参数POST请求
*
*@paramurl 请求路径
*@paramparams JSON格式请求参数
*@returnHTTP响应对象
*@throwsIOException 程序异常时抛出,由调用者处理*/
public static Response post(String url, String params) throwsIOException {return doPostRequest(url, null, params);
}/*** 发送JSON格式参数POST请求
*
*@paramurl 请求路径
*@paramheaders 请求头中设置的参数
*@paramparams JSON格式请求参数
*@returnHTTP响应对象
*@throwsIOException 程序异常时抛出,由调用者处理*/
public static Response post(String url, Map headers, String params) throwsIOException {returndoPostRequest(url, headers, params);
}/*** 字符串参数post请求
*
*@paramurl 请求URL地址
*@paramparamMap 请求字符串参数集合
*@returnHTTP响应对象
*@throwsIOException 程序异常时抛出,由调用者处理*/
public static Response post(String url, Map paramMap) throwsIOException {return doPostRequest(url, null, paramMap, null);
}/*** 带请求头的普通表单提交方式post请求
*
*@paramheaders 请求头参数
*@paramurl 请求URL地址
*@paramparamMap 请求字符串参数集合
*@returnHTTP响应对象
*@throwsIOException 程序异常时抛出,由调用者处理*/
public static Response post(Map headers, String url, Map paramMap) throwsIOException {return doPostRequest(url, headers, paramMap, null);
}/*** 带上传文件的post请求
*
*@paramurl 请求URL地址
*@paramparamMap 请求字符串参数集合
*@paramfileMap 请求文件参数集合
*@returnHTTP响应对象
*@throwsIOException 程序异常时抛出,由调用者处理*/
public static Response post(String url, Map paramMap, Map fileMap) throwsIOException {return doPostRequest(url, null, paramMap, fileMap);
}/*** 带请求头的上传文件post请求
*
*@paramurl 请求URL地址
*@paramheaders 请求头参数
*@paramparamMap 请求字符串参数集合
*@paramfileMap 请求文件参数集合
*@returnHTTP响应对象
*@throwsIOException 程序异常时抛出,由调用者处理*/
public static Response post(String url, Map headers, Map paramMap, Map fileMap) throwsIOException {returndoPostRequest(url, headers, paramMap, fileMap);
}/*** 执行post请求
*
*@paramurl 请求URL地址
*@paramheaders 请求头
*@paramjsonParams 请求JSON格式字符串参数
*@returnHTTP响应对象
*@throwsIOException 程序异常时抛出,由调用者处理*/
private static Response doPostRequest(String url, Map headers, String jsonParams) throwsIOException {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();returnresponse;
}/*** 普通表单方式发送POST请求
*
*@paramurl 请求URL地址
*@paramheaders 请求头
*@paramparamMap 请求字符串参数集合
*@paramfileMap 请求文件参数集合
*@returnHTTP响应对象
*@throwsIOException 程序异常时抛出,由调用者处理*/
private static Response doPostRequest(String url, Map headers, Map paramMap, Map fileMap) throwsIOException {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 inputStreamList = null;try{//添加文件参数
if (null != fileMap && !fileMap.isEmpty()) {
inputStreamList= new ArrayList();
InputStream in= null;
File file= null;for (Entrye : fileMap.entrySet()) {
file=e.getValue();
in= newFileInputStream(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();returnresponse;
}//关闭上传文件的输入流
finally{
closeStream(inputStreamList);
}
}/*** 关流
*
*@paramstreamList 流集合*/
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 voidgetTrust() {try{
HttpsURLConnection.setDefaultHostnameVerifier(newHostnameVerifier() {public booleanverify(String hostname, SSLSession session) {return true;
}
});
SSLContext context= SSLContext.getInstance("TLS");
context.init(null, new X509TrustManager[] { newX509TrustManager() {public void checkClientTrusted(X509Certificate[] chain, String authType) throwsCertificateException {}public void checkServerTrusted(X509Certificate[] chain, String authType) throwsCertificateException {}publicX509Certificate[] getAcceptedIssuers() {return new X509Certificate[0];
}
} },newSecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());
}catch(Exception e) {
e.printStackTrace();
}
}
}