package cn.com.baidu.util;
import cn.com.tenlion.util.smc.SMCHttpUtil;
import javax.net.ssl.*;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Map;
/**
* 网络请求工具类
* 2022年2月26日23:14:06
* 会飞的哈士奇
*/
public class HttpUtil {
/**
* 信任所有证书
* Start
*/
static {
try {
trustAllHttpsCertificates();
HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
public boolean verify(String urlHostName, SSLSession session) {
return true;
}
});
} catch (Exception e) {
}
}
private static void trustAllHttpsCertificates() throws NoSuchAlgorithmException, KeyManagementException {
TrustManager[] trustAllCerts = new TrustManager[1];
trustAllCerts[0] = new SMCHttpUtil.TrustAllManager();
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, null);
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
}
private static class TrustAllManager implements X509TrustManager {
public X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkServerTrusted(X509Certificate[] certs, String authType) throws CertificateException {
}
public void checkClientTrusted(X509Certificate[] certs, String authType) throws CertificateException {
}
}
/**
* 信任所有证书
* End
*/
/**
* Get请求
* @param getUrl 请求地址
* @param param 携带参数
* @param headers headers参数
* @return
* @throws Exception
*/
public static String doGet(String getUrl, Map<String, Object> param, Map<String, String> headers) throws Exception {
// 封装发送的请求参数
StringBuffer buffer = new StringBuffer();
if(param != null) {
buffer.append("?");
int x = 0;
for(Map.Entry<String, Object> map : param.entrySet()) {
buffer.append(map.getKey()).append("=").append(map.getValue().toString());
if(x != param.size()-1) {
buffer.append("&");
}
x++;
}
}
String urlPath = getUrl + buffer.toString();
URL url = new URL(urlPath);
URLConnection urlConnection = url.openConnection();
HttpURLConnection httpUrlConnection = (HttpURLConnection) urlConnection;
// 设置请求头属性参数
httpUrlConnection.setRequestProperty("charset", "UTF-8");
if(headers != null) {
for (Map.Entry<String, String> map : headers.entrySet()) {
httpUrlConnection.setRequestProperty(map.getKey(), map.getValue());
}
}
String response = "";// 响应内容
String status = "";// 响应状态6
PrintWriter out = null;
BufferedReader in = null;
try{
httpUrlConnection.connect();
// 定义BufferedReader输入流来读取URL的响应数据
in = new BufferedReader(new InputStreamReader(httpUrlConnection.getInputStream(), "UTF-8"));
String line;
while ((line = in.readLine()) != null) {
response += line;
}
// 获得URL的响应状态码
status = new Integer(httpUrlConnection.getResponseCode()).toString();
}catch(Exception e) {
e.printStackTrace();
}finally {
try {
if (out != null) { out.close();}
if (in != null) {in.close();}
} catch (Exception ex) {
ex.printStackTrace();
}
}
System.out.println("响应状态:" + status);
System.out.println("响应数据:" + response);
return response;
}
/**
* Post请求
* @param postUrl 请求地址
* @param param 请求参数
* @param headers headers参数
* @return
* @throws Exception
*/
public static String doPost(String postUrl, Map<String, Object> param, Map<String, String> headers) throws Exception {
// 封装发送的请求参数
StringBuffer buffer = new StringBuffer();
if(param != null) {
int x = 0;
for (Map.Entry<String, Object> map : param.entrySet()) {
buffer.append(map.getKey()).append("=").append(map.getValue().toString());
if (x != param.size() - 1) {
buffer.append("&");
}
x++;
}
}
URL url = new URL(postUrl);
URLConnection urlConnection = url.openConnection();
HttpURLConnection httpUrlConnection = (HttpURLConnection) urlConnection;
// 设置请求头属性参数
httpUrlConnection.setRequestProperty("charset", "UTF-8");
if(headers != null) {
for (Map.Entry<String, String> map : headers.entrySet()) {
httpUrlConnection.setRequestProperty(map.getKey(), map.getValue());
}
}
// 输入输出都打开
httpUrlConnection.setDoOutput(true);
httpUrlConnection.setDoInput(true);
String response = "";// 响应内容
String status = "";// 响应状态
PrintWriter out = null;
BufferedReader in = null;
try{
// 获取URLConnection对象对应的输出流
out = new PrintWriter(httpUrlConnection.getOutputStream());
// 发送请求参数
out.write(buffer.toString());
// flush输出流的缓冲
out.flush();
httpUrlConnection.connect();
// 定义BufferedReader输入流来读取URL的响应数据
in = new BufferedReader(new InputStreamReader(httpUrlConnection.getInputStream(), "UTF-8"));
String line;
while ((line = in.readLine()) != null) {
response += line;
}
// 获得URL的响应状态码
status = new Integer(httpUrlConnection.getResponseCode()).toString();
}catch(Exception e) {
e.printStackTrace();
}finally {
try {
if (out != null) { out.close();}
if (in != null) {in.close();}
} catch (Exception ex) {
ex.printStackTrace();
}
}
System.out.println("响应状态:" + status);
System.out.println("响应数据:" + response);
return response;
}
/**
* 携带Json串的网络请求
* @param hostUrl 请求地址
* @param requestType 请求类型 POST | DELETE | UPDATE
* @param json Json字符串
* @return
* @throws Exception
*/
public static String doJson(String hostUrl, String requestType, String json) throws Exception {
OutputStream out = null;
BufferedReader br = null;
String response = "";// 响应内容
String status = "";// 响应状态
try {
// 创建 URL
URL restUrl = new URL(hostUrl);
// 打开连接
HttpURLConnection httpUrlConnection = (HttpURLConnection) restUrl.openConnection();
// 设置请求方式
httpUrlConnection.setRequestMethod(requestType);
httpUrlConnection.setRequestProperty("Connection","keep-Alive");
//设置发送文件类型
httpUrlConnection.setRequestProperty("Content-Type","application/json");
// 输入输出都打开
httpUrlConnection.setDoOutput(true);
httpUrlConnection.setDoInput(true);
//开始连接
httpUrlConnection.connect();
// 传递参数流的方式
out = httpUrlConnection.getOutputStream();
out.write(json.getBytes());
out.flush();
// 读取数据
br = new BufferedReader(new InputStreamReader(httpUrlConnection.getInputStream(),"utf-8"));
String line = null;
while (null != (line=br.readLine())){
response += line;
}
// 获得URL的响应状态码
status = new Integer(httpUrlConnection.getResponseCode()).toString();
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
if (out != null) { out.close();}
if (br != null) {br.close();}
} catch (Exception ex) {
ex.printStackTrace();
}
}
System.out.println("响应状态:" + status);
System.out.println("响应数据:" + response);
return response;
}
}
|