375 lines
14 KiB
Java
375 lines
14 KiB
Java
|
||
package com.shenghua.utils;
|
||
|
||
import org.apache.commons.lang3.StringUtils;
|
||
import org.slf4j.Logger;
|
||
import org.slf4j.LoggerFactory;
|
||
import org.springframework.web.context.request.RequestContextHolder;
|
||
import org.springframework.web.context.request.ServletRequestAttributes;
|
||
|
||
import javax.net.ssl.*;
|
||
import javax.servlet.http.HttpServletRequest;
|
||
import java.io.*;
|
||
import java.net.HttpURLConnection;
|
||
import java.net.URL;
|
||
import java.net.URLConnection;
|
||
import java.nio.charset.StandardCharsets;
|
||
import java.security.cert.CertificateException;
|
||
import java.security.cert.X509Certificate;
|
||
import java.util.List;
|
||
import java.util.Map;
|
||
|
||
|
||
/**
|
||
* http context工具类
|
||
*/
|
||
public class HttpUtils {
|
||
|
||
private static final Logger log = LoggerFactory.getLogger(HttpUtils.class);
|
||
|
||
private static int connectTimeout = 3000;
|
||
private static int ios_connectTimeout = 10000;
|
||
|
||
private static class TrustAnyTrustManager implements 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[]{};
|
||
}
|
||
}
|
||
|
||
private static class TrustAnyHostnameVerifier implements HostnameVerifier {
|
||
public boolean verify(String hostname, SSLSession session) {
|
||
return true;
|
||
}
|
||
}
|
||
|
||
public static String sendGet(String url) {
|
||
String result = "";
|
||
BufferedReader in = null;
|
||
try {
|
||
// String urlNameString = url;
|
||
URL realUrl = new URL(url);
|
||
|
||
// 打开和URL之间的连接
|
||
URLConnection connection = realUrl.openConnection();
|
||
|
||
// 设置通用的请求属性
|
||
connection.setRequestProperty("accept", "*/*");
|
||
connection.setRequestProperty("connection", "Keep-Alive");
|
||
connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
|
||
|
||
// 建立实际的连接
|
||
connection.connect();
|
||
|
||
// 获取所有响应头字段
|
||
Map<String, List<String>> map = connection.getHeaderFields();
|
||
|
||
// 遍历所有的响应头字段
|
||
for (String key : map.keySet()) {
|
||
System.out.println(key + "--->" + map.get(key));
|
||
}
|
||
|
||
// 定义 BufferedReader输入流来读取URL的响应
|
||
in = new BufferedReader(new InputStreamReader(
|
||
connection.getInputStream()));
|
||
String line;
|
||
while ((line = in.readLine()) != null) {
|
||
result += line;
|
||
}
|
||
} catch (Exception e) {
|
||
System.out.println("发送GET请求出现异常!" + e);
|
||
e.printStackTrace();
|
||
}
|
||
|
||
// 使用finally块来关闭输入流
|
||
finally {
|
||
try {
|
||
if (in != null) {
|
||
in.close();
|
||
}
|
||
} catch (Exception e2) {
|
||
e2.printStackTrace();
|
||
}
|
||
}
|
||
return result;
|
||
}
|
||
|
||
/**
|
||
* @param url
|
||
* @param param
|
||
* @return
|
||
*/
|
||
public static String sendGet(String url, String param) {
|
||
String result = "";
|
||
BufferedReader in = null;
|
||
try {
|
||
String urlNameString = url + "?" + param;
|
||
URL realUrl = new URL(urlNameString);
|
||
// 打开和URL之间的连接
|
||
URLConnection connection = realUrl.openConnection();
|
||
// 设置通用的请求属性
|
||
connection.setRequestProperty("accept", "*/*");
|
||
connection.setRequestProperty("connection", "Keep-Alive");
|
||
connection.setRequestProperty("xm-sign","d9fdda2188c52dc128cd0d3ba157f957(79)1626234305702(74)1626232895270");
|
||
connection.setRequestProperty("user-agent",
|
||
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
|
||
// 建立实际的连接
|
||
connection.connect();
|
||
|
||
// 定义 BufferedReader输入流来读取URL的响应
|
||
in = new BufferedReader(new InputStreamReader(
|
||
connection.getInputStream()));
|
||
String line;
|
||
while ((line = in.readLine()) != null) {
|
||
result += line;
|
||
}
|
||
} catch (Exception e) {
|
||
System.out.println("发送GET请求出现异常!" + e);
|
||
e.printStackTrace();
|
||
}
|
||
// 使用finally块来关闭输入流
|
||
finally {
|
||
try {
|
||
if (in != null) {
|
||
in.close();
|
||
}
|
||
} catch (Exception e2) {
|
||
e2.printStackTrace();
|
||
}
|
||
}
|
||
return result;
|
||
}
|
||
|
||
public static String sendSSLPost(String url, String param) {
|
||
try {
|
||
SSLContext sc = SSLContext.getInstance("SSL");
|
||
sc.init(null, new TrustManager[]{new TrustAnyTrustManager()}, new java.security.SecureRandom());
|
||
URL console = new URL(url);
|
||
HttpsURLConnection conn = (HttpsURLConnection) console.openConnection();
|
||
conn.setSSLSocketFactory(sc.getSocketFactory());
|
||
conn.setHostnameVerifier(new TrustAnyHostnameVerifier());
|
||
conn.setRequestMethod("POST");
|
||
conn.setRequestProperty("Content-Type", "application/json");
|
||
conn.setRequestProperty("Proxy-Connection", "Keep-Alive");
|
||
conn.setConnectTimeout(ios_connectTimeout);
|
||
conn.setDoInput(true);
|
||
conn.setDoOutput(true);
|
||
BufferedOutputStream hurlBufOus = new BufferedOutputStream(conn.getOutputStream());
|
||
hurlBufOus.write(param.getBytes(StandardCharsets.UTF_8));
|
||
hurlBufOus.flush();
|
||
|
||
InputStream is = conn.getInputStream();
|
||
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
|
||
StringBuffer result = new StringBuffer();
|
||
String line;
|
||
while ((line = reader.readLine()) != null) {
|
||
result.append(line);
|
||
}
|
||
return result.toString();
|
||
} catch (Exception e) {
|
||
// log.error("[" + BaseConstants.LOG_FLAG_PRE_ERROR + "http]:", e);
|
||
return null;
|
||
}
|
||
}
|
||
|
||
public static String sendPost(String url, String param) {
|
||
try {
|
||
URLConnection conn = null;
|
||
|
||
URL realUrl = new URL(url);
|
||
// 打开和URL之间的连接
|
||
conn = realUrl.openConnection();
|
||
// 设置通用的请求属性
|
||
conn.setRequestProperty("accept", "*/*");
|
||
conn.setRequestProperty("connection", "Keep-Alive");
|
||
conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
|
||
// 发送POST请求必须设置如下两行
|
||
conn.setDoOutput(true);
|
||
conn.setDoInput(true);
|
||
conn.setConnectTimeout(connectTimeout);
|
||
try (PrintWriter out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(), StandardCharsets.UTF_8))) {
|
||
out.print(param);
|
||
out.flush();
|
||
try (BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8))) {
|
||
StringBuffer result = new StringBuffer();
|
||
String line;
|
||
while ((line = in.readLine()) != null) {
|
||
result.append(line);
|
||
}
|
||
return result.toString();
|
||
}
|
||
}
|
||
} catch (IOException e) {
|
||
e.printStackTrace();
|
||
}
|
||
return null;
|
||
}
|
||
|
||
|
||
/**
|
||
* Http post的工具方法
|
||
*
|
||
* @param httpUrl 请求地址
|
||
* @param data 请求数据
|
||
* @param connectTimeout 连接超时时间
|
||
* @param readTimeout 读取超时时间
|
||
* @param headers 请求头
|
||
* @return 将响应body作为String返回
|
||
* @throws IOException 请求中的IO异常
|
||
*/
|
||
public static String sendPost(String httpUrl, String contentType, String data, int connectTimeout, int readTimeout, Map<String, String> headers) {
|
||
OutputStream output = null;
|
||
InputStream in = null;
|
||
HttpURLConnection urlConnection = null;
|
||
BufferedReader bufferedReader = null;
|
||
InputStreamReader inputStreamReader = null;
|
||
try {
|
||
URL url = new URL(httpUrl);
|
||
urlConnection = (HttpURLConnection) url.openConnection();
|
||
urlConnection.setRequestMethod("POST");
|
||
urlConnection.setDoOutput(true);
|
||
urlConnection.setDoInput(true);
|
||
urlConnection.setRequestProperty("Content-Type", contentType);
|
||
if (headers != null) {
|
||
for (String key : headers.keySet()) {
|
||
urlConnection.setRequestProperty(key, headers.get(key));
|
||
}
|
||
}
|
||
urlConnection.setConnectTimeout(connectTimeout);
|
||
urlConnection.setReadTimeout(readTimeout);
|
||
urlConnection.connect();
|
||
// 发送数据
|
||
output = urlConnection.getOutputStream();
|
||
output.write(data.getBytes(StandardCharsets.UTF_8));
|
||
output.flush();
|
||
// 读取响应
|
||
if (urlConnection.getResponseCode() < 400) {
|
||
in = urlConnection.getInputStream();
|
||
} else {
|
||
in = urlConnection.getErrorStream();
|
||
}
|
||
inputStreamReader = new InputStreamReader(in, StandardCharsets.UTF_8);
|
||
bufferedReader = new BufferedReader(inputStreamReader);
|
||
StringBuilder strBuf = new StringBuilder();
|
||
String str;
|
||
while ((str = bufferedReader.readLine()) != null) {
|
||
strBuf.append(str);
|
||
}
|
||
return strBuf.toString();
|
||
} catch (Exception ignored) {
|
||
} finally {
|
||
try {
|
||
if (bufferedReader != null) {
|
||
bufferedReader.close();
|
||
}
|
||
if (inputStreamReader != null) {
|
||
inputStreamReader.close();
|
||
}
|
||
if (in != null) {
|
||
in.close();
|
||
}
|
||
if (urlConnection != null) {
|
||
urlConnection.disconnect();
|
||
}
|
||
} catch (IOException ignored) {
|
||
}
|
||
}
|
||
return null;
|
||
}
|
||
|
||
public static HttpServletRequest getHttpServletRequest() {
|
||
return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
|
||
}
|
||
|
||
public static String getDomain() {
|
||
HttpServletRequest request = getHttpServletRequest();
|
||
StringBuffer url = request.getRequestURL();
|
||
return url.delete(url.length() - request.getRequestURI().length(), url.length()).toString();
|
||
}
|
||
|
||
public static String getOrigin() {
|
||
HttpServletRequest request = getHttpServletRequest();
|
||
return request.getHeader("Origin");
|
||
}
|
||
|
||
/**
|
||
* 获取request中body数据
|
||
*
|
||
* @param request
|
||
* @return
|
||
*/
|
||
public static String getBody(HttpServletRequest request) {
|
||
StringBuilder sb = new StringBuilder();
|
||
try (InputStream inputStream = request.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));) {
|
||
String line = "";
|
||
while ((line = reader.readLine()) != null) {//todo 换行
|
||
sb.append(line);
|
||
}
|
||
} catch (IOException ex) {
|
||
ex.printStackTrace();
|
||
}
|
||
return sb.toString();
|
||
}
|
||
|
||
public static byte[] getByteArrBody(HttpServletRequest request) {
|
||
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
|
||
try (InputStream inputStream = request.getInputStream(); BufferedInputStream byteOutputStream = new BufferedInputStream(inputStream);) {
|
||
byte[] bytes = new byte[1024];
|
||
int a;
|
||
while ((a = byteOutputStream.read(bytes)) != -1) {
|
||
byteArrayOutputStream.write(bytes, 0, a);
|
||
}
|
||
} catch (IOException ex) {
|
||
ex.printStackTrace();
|
||
}
|
||
return byteArrayOutputStream.toByteArray();
|
||
}
|
||
|
||
/**
|
||
* 获取request中body数据
|
||
*
|
||
* @param request
|
||
* @return
|
||
*/
|
||
public static String writeToBody(HttpServletRequest request, Map<String, Serializable> params) {
|
||
StringBuilder sb = new StringBuilder();
|
||
try (InputStream inputStream = request.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));) {
|
||
String line = "";
|
||
while ((line = reader.readLine()) != null) {//todo 换行
|
||
sb.append(line);
|
||
}
|
||
} catch (IOException ex) {
|
||
ex.printStackTrace();
|
||
}
|
||
return sb.toString();
|
||
}
|
||
|
||
|
||
public static String getRealClientIp(HttpServletRequest request) {
|
||
String ip = request.getHeader("x-forwarded-for");
|
||
if (ip != null) {
|
||
ip = ip.split(",")[0];
|
||
}
|
||
if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
|
||
ip = request.getHeader("Proxy-Client-IP");
|
||
}
|
||
if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
|
||
ip = request.getHeader("WL-Proxy-Client-IP");
|
||
}
|
||
if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
|
||
ip = request.getHeader("X-Real-IP");
|
||
}
|
||
if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
|
||
ip = request.getRemoteAddr();
|
||
}
|
||
return ip;
|
||
}
|
||
|
||
}
|