影视会员
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

618 lines
22 KiB

package com.cyjd.rights.utils;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.http.HeaderIterator;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.util.EntityUtils;
import javax.net.ssl.*;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
@Slf4j
public class HttpUtils {
private static OkHttpClient client = new OkHttpClient();
private static final String sign_private_key = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCfNNNAUdIQHji6oWYTLogbLjT8rOdPPtUhb1a8fqucRcDA4lQmQw7AZD4gDlEq1tRyVU8nJTPTWS8hwfAC3G55d/Sgux8GRaMUuUrMJ0GcNrOo56Bwyh9cJP+n66pQoLo/2xVbE/dYKUKhM32JnmdrP8vjP0jFuCxw4MCZWVJmjohZ72nu+EYtFmef+0mKRFQqm7/2g3lYr93ICZfWE5F75WqT0PNLB6rWEiNM+r7V5+7fJfA35DmFVbb0cDzyiZ3pRdpGBplv54jTns1hk3yunE/Nlj+xvrz2/rsRFeWfyfPx2Bd95LkCxiJrpK7Ui9Fwg0GNVrJmA5pcqWut1mEpAgMBAAECggEAEGNFo4dIkjQqLrvSYAMYK4QUHDZIERYspiZpzTlUvN9JOhGSC+Y3LIKlCnOu0zQN5j71yNfBf+3cNiNaa1D5ZjN80NayGNkuMkHoex9HV6ch0y8Uisejdr6wOj6951LEGTKZ/igN+9szaph8QaA2kQmeGSQ4f3G30V6xNJfHLZswcQT0D7qDA/bpcdaJ0/6BDObklQx/lD5kWuUmW7TUp7Hp8eEt0z0XCsgzem5+z4rzMhnyIIXle1YqRklnZKWAYbUplBx+RVTyQdLVoSREfGo8/BUDBY7Da5SihMKtVMj0CP1B+nZDE2fWjUOW28L/xZp1IiG9r/QqpvDPhATQAQKBgQDlvHpqAIEnc03WjYgbpbF1bW6qoyj+KYTWhjAB5frOomLd2uPn0br9YSlMn8q/7i9nOQEzLWAuKrQjRc49w9cbFdgj78FxUH7V9ntRZUeZraEGvOG2z9U4JTdTp9JI/cXWPwA6iv/RPKJR7q1Cfz12NQZ78DyQs01e3gjUZkBcKQKBgQCxaDNO1pypJLmPwNyJZ3uukSh5IdPkbMwidJFcOUrDb9cJWlDcQAngsR/amWEhNYYuqHP3T+J1tu9iyZaf2qVEFtedi9m/iyLjouJitnmqqZjLSsQ0FYe6ApQYC8osZuG0INg0sjiPq54CicmnGhypYhw0BW1SSJ0WajtAWKZ9AQKBgDpwcndKf5AofZFpWUknIfgsCS2w6XmV2Cu14Lpq5RzxI9MpnjXXHQjdUWMjdrDSBw7r6kk5brDvvfkHBcqiabKDIQMrNvr7LfiBhacT613FVCPhok0dmzB4DxXhp9VXcJ7qUcWSnDZ+hQ/wdfRnZ5wNKwQV/WIVqkXKl1ZoWFDZAoGBAKoS5v0xqUZOOsahccsYNe4IovBdibF2y8xMS/5Jvm7WDSSePN6pVc7ef1clq4QWt+iK/YGeR8/p7FycPZZKGh3IeDRFGh8S2AO656USolkF9cEOkEIOUev1BNx4kP04NDBnPF5obOju8bAlP/i+g7OuprMIcOFtU4tllB//3LwBAoGAOY9xTmyYACLC3kYYb+iBnzq/h6cywEUjsPSfy3XeDyFXfDM2h41O2Le7UdNpEljCQdTTYTPqzhywm1/AOgdMv0vWcUZKZmklC1atAFhZnVQ8fVRgv5ZhhmXzGXjlflUTuYlr99v7Csz8q+Tu0/AbLCeAqEFgvEDS/WS3tdTmnHA=";
public static String postJson(String url, String json) {
log.info("http util post:" + url + "param:" + json);
Request request = new Request.Builder().url(url).
post(RequestBody.create(MediaType.parse("application/json"), json)).build();
String string = null;
try {
Response response = client.newCall(request).execute();
if (!response.isSuccessful()) {
throw new IOException("Unexpected code " + response);
}
string = response.body().string();
log.info("http util post result:" + string);
} catch (Exception e) {
log.info(e.getMessage());
}
return string;
}
public static ResponseBody postFile(String url, String json) {
log.info("http util post:" + url);
Request request = new Request.Builder().url(url).
post(RequestBody.create(MediaType.parse("application/json"), json)).build();
String string = null;
ResponseBody body = null;
try {
Response response = client.newCall(request).execute();
if (!response.isSuccessful()) {
throw new IOException("Unexpected code " + response);
}
body = response.body();
log.info("http util post result:" + string);
} catch (Exception e) {
log.info(e.getMessage());
}
return body;
}
public static String postJsonHeBei(String url, String json) {
log.info("http util post:" + url + "param:" + json);
Request request = new Request.Builder().url(url).
post(RequestBody.create(MediaType.parse("application/json"), json)).addHeader("charset", "GBK").build();
String string = null;
Response response = null;
System.out.println(request.headers());
try {
response = client.newCall(request).execute();
;
if (!response.isSuccessful()) {
throw new IOException("Unexpected code " + response);
}
string = response.body().string();
System.out.println(string);
log.info("http util post result:" + string);
} catch (Exception e) {
log.info(e.getMessage());
}
return string;
}
public static String get(String url) {
log.info("http util get:" + url);
Request request = new Request.Builder().url(url).get().build();
String result = "";
try {
Response response = client.newCall(request).execute();
if (!response.isSuccessful()) {
throw new IOException("Unexpected code " + response);
}
result = response.body().string();
log.info("http util get result:" + result);
} catch (IOException e) {
log.info("request error" + e.getMessage());
}
return result;
}
/**
* @param url
* @return
* @throws IOException
* @Description get请求
*/
public static String sendGet(String url) {
System.out.println(url);
// 输入流
InputStream is = null;
BufferedReader br = null;
String result = null;
// 创建httpClient实例
HttpClient httpClient = new HttpClient();
// 设置http连接主机服务超时时间:15000毫秒
// 先获取连接管理器对象,再获取参数对象,再进行参数的赋值
httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(15000);
// 创建一个Get方法实例对象
GetMethod getMethod = new GetMethod(url);
// 设置get请求超时为15000毫秒
getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 15000);
// 设置请求重试机制,默认重试次数:3次,参数设置为true,重试机制可用,false相反
getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, true));
try {
// 执行Get方法
int statusCode = httpClient.executeMethod(getMethod);
// 判断返回码
if (statusCode != HttpStatus.SC_OK) {
// 如果状态码返回的不是ok,说明失败了,打印错误信息
log.error("Method faild: " + getMethod.getStatusLine());
} else {
// 通过getMethod实例,获取远程的一个输入流
is = getMethod.getResponseBodyAsStream();
// 包装输入流
br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
StringBuffer sbf = new StringBuffer();
// 读取封装的输入流
String temp = null;
while ((temp = br.readLine()) != null) {
sbf.append(temp).append("\r\n");
}
result = sbf.toString();
System.out.println(result);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
// 关闭资源
if (null != br) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != is) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// 释放连接
getMethod.releaseConnection();
}
return result;
}
/**
* @param url
* @return
* @throws IOException
* @Description get请求 GB2312编码
*/
public static String sendGetGB(String url) {
// 输入流
InputStream is = null;
BufferedReader br = null;
String result = null;
// 创建httpClient实例
HttpClient httpClient = new HttpClient();
// 设置http连接主机服务超时时间:15000毫秒
// 先获取连接管理器对象,再获取参数对象,再进行参数的赋值
httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(15000);
// 创建一个Get方法实例对象
GetMethod getMethod = new GetMethod(url);
// 设置get请求超时为15000毫秒
getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 15000);
// 设置请求重试机制,默认重试次数:3次,参数设置为true,重试机制可用,false相反
getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, true));
try {
// 执行Get方法
int statusCode = httpClient.executeMethod(getMethod);
// 判断返回码
if (statusCode != HttpStatus.SC_OK) {
// 如果状态码返回的不是ok,说明失败了,打印错误信息
log.error("Method faild: " + getMethod.getStatusLine());
} else {
// 通过getMethod实例,获取远程的一个输入流
is = getMethod.getResponseBodyAsStream();
// 包装输入流
br = new BufferedReader(new InputStreamReader(is, "GB2312"));
StringBuffer sbf = new StringBuffer();
// 读取封装的输入流
String temp = null;
while ((temp = br.readLine()) != null) {
sbf.append(temp).append("\r\n");
}
result = sbf.toString();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
// 关闭资源
if (null != br) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != is) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// 释放连接
getMethod.releaseConnection();
}
return result;
}
/**
* 向指定 URL 发送POST方法的请求
*
* @param url 发送请求的 URL
* @param param 请求参数请求参数应该是 name1=value1&name2=value2 的形式
* @return 所代表远程资源的响应结果
*/
public static String sendPost(String url, String param) {
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
log.info("post" + url + param);
// 打开和URL之间的连接
URLConnection conn = realUrl.openConnection();
// 设置通用的请求属性
conn.setRequestProperty("content-type", "application/x-www-form-urlencoded");
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
// 获取URLConnection对象对应的输出流
out = new PrintWriter(conn.getOutputStream());
// 发送请求参数
out.print(param);
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
log.info("发送 POST 请求出现异常!" + e);
e.printStackTrace();
}
//使用finally块来关闭输出流、输入流
finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
log.info(result);
return result;
}
/**
* 向指定 URL 发送POST方法的请求
*
* @param url 发送请求的 URL
* @param param 请求参数
* @return 所代表远程资源的响应结果
*/
public static String sendPostJSON(String url, String param) {
System.out.println(url);
System.out.println(param);
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
log.info("post" + url + param);
// 打开和URL之间的连接
URLConnection conn = realUrl.openConnection();
// 设置通用的请求属性
conn.setRequestProperty("content-type", "application/json");
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setReadTimeout(30000);
conn.setConnectTimeout(30000);
// 获取URLConnection对象对应的输出流
out = new PrintWriter(conn.getOutputStream());
// 发送请求参数
out.print(param);
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
log.info("发送 POST 请求出现异常!" + e);
e.printStackTrace();
}
//使用finally块来关闭输出流、输入流
finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
log.info(result);
return result;
}
public static String sendGetParam(String url, String param) {
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
// 打开和URL之间的连接
URLConnection conn = realUrl.openConnection();
// 设置通用的请求属性
conn.setRequestProperty("content-type", "application/x-www-form-urlencoded");
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
// 获取URLConnection对象对应的输出流
out = new PrintWriter(conn.getOutputStream());
// 发送请求参数
out.print(param);
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
log.info("发送 POST 请求出现异常!" + e);
e.printStackTrace();
}
//使用finally块来关闭输出流、输入流
finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return result;
}
//url编码
public static String getURLEncoderString(String str) {
String result = "";
if (null == str) {
return "";
}
try {
result = URLEncoder.encode(str, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return result;
}
//url解码
public static String URLDecoderString(String str) {
String result = "";
if (null == str) {
return "";
}
try {
result = URLDecoder.decode(str, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return result;
}
public static String readHttpResponse(HttpResponse httpResponse) throws ParseException, IOException {
StringBuilder builder = new StringBuilder();
// 获取响应消息实体
HttpEntity entity = httpResponse.getEntity();
// 响应状态
builder.append("status:" + httpResponse.getStatusLine());
builder.append("headers:");
HeaderIterator iterator = httpResponse.headerIterator();
while (iterator.hasNext()) {
builder.append("\t" + iterator.next());
}
// 判断响应实体是否为空
if (entity != null) {
String responseString = EntityUtils.toString(entity);
builder.append("response length:" + responseString.length());
builder.append("response content:" + responseString.replace("\r\n", ""));
}
return builder.toString();
}
/**
* @param url
* @return
* @throws IOException
* @Description get请求
*/
public static String sendGetAddHead(String url, String head) throws HttpException, IOException {
System.out.println(url);
// 输入流
InputStream is = null;
BufferedReader br = null;
String result = null;
// 创建httpClient实例
HttpClient httpClient = new HttpClient();
// 设置http连接主机服务超时时间:15000毫秒
// 先获取连接管理器对象,再获取参数对象,再进行参数的赋值
httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(10000);
// 创建一个Get方法实例对象
GetMethod getMethod = new GetMethod(url);
getMethod.addRequestHeader("Access-Token", head);
// 设置get请求超时为15000毫秒
getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 10000);
// 设置请求重试机制,默认重试次数:3次,参数设置为true,重试机制可用,false相反
getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, true));
try {
// 执行Get方法
int statusCode = httpClient.executeMethod(getMethod);
// 判断返回码
if (statusCode != HttpStatus.SC_OK) {
// 如果状态码返回的不是ok,说明失败了,打印错误信息
log.error("Method faild: " + getMethod.getStatusLine());
} else {
// 通过getMethod实例,获取远程的一个输入流
is = getMethod.getResponseBodyAsStream();
// 包装输入流
br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
StringBuffer sbf = new StringBuffer();
// 读取封装的输入流
String temp = null;
while ((temp = br.readLine()) != null) {
sbf.append(temp).append("\r\n");
}
result = sbf.toString();
System.out.println(result);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
// 关闭资源
if (null != br) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != is) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// 释放连接
getMethod.releaseConnection();
}
return result;
}
/**
* description 忽略https证书验证
*
* @author yanzy
* @version 1.0
* @date 2021/9/8 14:42
*/
public static HostnameVerifier getHostnameVerifier() {
HostnameVerifier hostnameVerifier = new HostnameVerifier() {
@Override
public boolean verify(String s, SSLSession sslSession) {
return true;
}
};
return hostnameVerifier;
}
public static SSLSocketFactory getSSLSocketFactory() {
try {
SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, getTrustManager(), new SecureRandom());
return sslContext.getSocketFactory();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private static TrustManager[] getTrustManager() {
TrustManager[] trustAllCerts = new TrustManager[]{
new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) {
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[]{};
}
}
};
return trustAllCerts;
}
}