package com.example.utils;
|
|
|
import cn.hutool.json.JSONUtil;
|
import lombok.extern.slf4j.Slf4j;
|
import org.apache.http.HttpEntity;
|
import org.apache.http.HttpResponse;
|
import org.apache.http.NameValuePair;
|
import org.apache.http.client.ClientProtocolException;
|
import org.apache.http.client.HttpClient;
|
import org.apache.http.client.config.RequestConfig;
|
import org.apache.http.client.entity.UrlEncodedFormEntity;
|
import org.apache.http.client.methods.CloseableHttpResponse;
|
import org.apache.http.client.methods.HttpGet;
|
import org.apache.http.client.methods.HttpPost;
|
import org.apache.http.conn.ssl.DefaultHostnameVerifier;
|
import org.apache.http.conn.util.PublicSuffixMatcher;
|
import org.apache.http.conn.util.PublicSuffixMatcherLoader;
|
import org.apache.http.entity.StringEntity;
|
import org.apache.http.impl.client.CloseableHttpClient;
|
import org.apache.http.impl.client.HttpClients;
|
import org.apache.http.message.BasicNameValuePair;
|
import org.apache.http.util.EntityUtils;
|
import org.springframework.stereotype.Component;
|
import java.io.*;
|
import java.net.HttpURLConnection;
|
import java.net.URL;
|
import java.net.URLEncoder;
|
import java.nio.charset.StandardCharsets;
|
import java.util.ArrayList;
|
import java.util.List;
|
import java.util.Map;
|
import java.util.UUID;
|
|
|
/**
|
* httpClient 工具类
|
*
|
* @create 2019-02-10 下午 2:49
|
*/
|
@Component
|
@Slf4j
|
public class HttpClientUtils {
|
|
/**
|
* 默认参数设置
|
* setConnectTimeout:设置连接超时时间,单位毫秒。
|
* setConnectionRequestTimeout:设置从connect Manager获取Connection 超时时间,单位毫秒。
|
* setSocketTimeout:请求获取数据的超时时间,单位毫秒。访问一个接口,多少时间内无法返回数据,就直接放弃此次调用。 暂时定义15分钟
|
*/
|
private RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(600000).setConnectTimeout(600000).setConnectionRequestTimeout(600000).build();
|
|
/**
|
* 静态内部类---作用:单例产生类的实例
|
*
|
* @author Administrator
|
*/
|
private static class LazyHolder {
|
private static final HttpClientUtils INSTANCE = new HttpClientUtils();
|
|
}
|
|
HttpClientUtils() {
|
}
|
|
public static HttpClientUtils getInstance() {
|
return LazyHolder.INSTANCE;
|
}
|
|
/**
|
* 发送 post请求
|
*
|
* @param httpUrl 地址
|
*/
|
public String sendHttpPost(String httpUrl) {
|
HttpPost httpPost = new HttpPost(httpUrl);// 创建httpPost
|
return sendHttpPost(httpPost);
|
}
|
|
/**
|
* 发送 post请求
|
*
|
* @param httpUrl 地址
|
* @param params 参数(格式:key1=value1&key2=value2)
|
*/
|
public String sendHttpPost(String httpUrl, String params) {
|
HttpPost httpPost = new HttpPost(httpUrl);// 创建httpPost
|
try {
|
//设置参数
|
StringEntity stringEntity = new StringEntity(params, "UTF-8");
|
stringEntity.setContentType("application/x-www-form-urlencoded");
|
httpPost.setEntity(stringEntity);
|
} catch (Exception e) {
|
e.printStackTrace();
|
}
|
return sendHttpPost(httpPost);
|
}
|
|
|
public static String sendPost(String httpUrl, Map<String, Object> maps,Map<String ,Object> headers) {
|
|
try {
|
// 1. 创建 URL 对象
|
URL url = new URL(httpUrl);
|
// 2. 创建 HttpURLConnection 对象
|
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
|
// 3. 设置请求方法为 POST
|
connection.setRequestMethod("POST");
|
// 4. 设置 Content-Type 头部字段
|
connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
|
if (headers != null && !headers.isEmpty()){
|
for (Map.Entry<String, Object> entry : headers.entrySet()) {
|
connection.setRequestProperty(entry.getKey(), entry.getValue().toString());
|
}
|
}
|
// 6. 向服务器发送数据
|
String requestBody = JSONUtil.toJsonStr(maps);
|
log.info(httpUrl+"入参: "+requestBody);
|
log.info("请求头 ->{}",JSONUtil.toJsonStr(headers));
|
// String requestBody1 = maps.toString();
|
byte[] postData = requestBody.getBytes(StandardCharsets.UTF_8);
|
connection.setDoOutput(true);
|
try (OutputStream outputStream = connection.getOutputStream()) {
|
outputStream.write(postData);
|
}
|
|
// 8. 获取响应数据
|
try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
|
String line;
|
StringBuilder response = new StringBuilder();
|
while ((line = reader.readLine()) != null) {
|
response.append(line);
|
}
|
log.info("=====================================================");
|
log.info(httpUrl+"出参");
|
log.info(response.toString());
|
connection.disconnect();
|
return response.toString();
|
}
|
} catch (IOException e) {
|
e.printStackTrace();
|
}
|
|
return null;
|
}
|
|
public static String sendPost(String httpUrl, String json) {
|
|
try {
|
// 1. 创建 URL 对象
|
URL url = new URL(httpUrl);
|
// 2. 创建 HttpURLConnection 对象
|
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
|
// 3. 设置请求方法为 POST
|
connection.setRequestMethod("POST");
|
// 4. 设置 Content-Type 头部字段
|
connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
|
// 6. 向服务器发送数据
|
String requestBody = json;
|
log.info(httpUrl+"入参: "+requestBody);
|
// String requestBody1 = maps.toString();
|
byte[] postData = requestBody.getBytes(StandardCharsets.UTF_8);
|
connection.setDoOutput(true);
|
try (OutputStream outputStream = connection.getOutputStream()) {
|
outputStream.write(postData);
|
}
|
|
// 8. 获取响应数据
|
try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
|
String line;
|
StringBuilder response = new StringBuilder();
|
while ((line = reader.readLine()) != null) {
|
response.append(line);
|
}
|
log.info("=====================================================");
|
log.info(httpUrl+"出参");
|
log.info(response.toString());
|
connection.disconnect();
|
return response.toString();
|
}
|
} catch (IOException e) {
|
e.printStackTrace();
|
}
|
|
return null;
|
}
|
|
public static String sendPostToken(String httpUrl, Map<String, Object> maps,String authorization) {
|
|
try {
|
// 1. 创建 URL 对象
|
URL url = new URL(httpUrl);
|
// 2. 创建 HttpURLConnection 对象
|
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
|
// 3. 设置请求方法为 POST
|
connection.setRequestMethod("POST");
|
// 4. 设置 Content-Type 头部字段
|
connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
|
connection.setRequestProperty("Authorization", authorization);
|
// 6. 向服务器发送数据
|
String requestBody = JSONUtil.toJsonStr(maps);
|
log.info(httpUrl+"入参: "+requestBody);
|
// String requestBody1 = maps.toString();
|
byte[] postData = requestBody.getBytes("UTF-8");
|
connection.setDoOutput(true);
|
try (OutputStream outputStream = connection.getOutputStream()) {
|
outputStream.write(postData);
|
}
|
|
// 8. 获取响应数据
|
try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
|
String line;
|
StringBuilder response = new StringBuilder();
|
while ((line = reader.readLine()) != null) {
|
response.append(line);
|
}
|
log.info("=====================================================");
|
log.info(httpUrl+"出参");
|
log.info(response.toString());
|
connection.disconnect();
|
return response.toString();
|
}
|
} catch (IOException e) {
|
e.printStackTrace();
|
}
|
|
return null;
|
}
|
|
public static String sendPostTokenFormUrlencoded(String httpUrl, Map<String, Object> maps, String authorization) {
|
HttpURLConnection connection = null;
|
OutputStreamWriter writer = null;
|
BufferedReader reader = null;
|
StringBuilder response = new StringBuilder();
|
try {
|
log.info("请求地址 ->{}",httpUrl);
|
URL url = new URL(httpUrl);
|
connection = (HttpURLConnection) url.openConnection();
|
connection.setRequestMethod("POST");
|
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
|
if (authorization != null && !authorization.isEmpty()) {
|
connection.setRequestProperty("Authorization", authorization);
|
}
|
connection.setDoOutput(true);
|
StringBuilder postData = new StringBuilder();
|
log.info("入参 ->{}", JSONUtil.toJsonStr(maps));
|
for (Map.Entry<String, Object> entry : maps.entrySet()) {
|
if (postData.length() > 0) {
|
postData.append("&");
|
}
|
postData.append(URLEncoder.encode(entry.getKey(), "UTF-8"))
|
.append("=")
|
.append(URLEncoder.encode(entry.getValue().toString(), "UTF-8"));
|
}
|
log.info("参数拼接 ->{}",postData);
|
writer = new OutputStreamWriter(connection.getOutputStream());
|
writer.write(postData.toString());
|
writer.flush();
|
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
|
String line;
|
while ((line = reader.readLine()) != null) {
|
response.append(line);
|
}
|
log.info("返回 ->{}",response);
|
} catch (Exception e) {
|
e.printStackTrace();
|
return null;
|
} finally {
|
try {
|
if (writer != null) writer.close();
|
if (reader != null) reader.close();
|
} catch (IOException e) {
|
e.printStackTrace();
|
}
|
if (connection != null) {
|
connection.disconnect();
|
}
|
}
|
return response.toString();
|
}
|
|
public static String sendPostTokenFormData(String httpUrl, Map<String, Object> maps, String authorization) {
|
HttpURLConnection connection = null;
|
DataOutputStream outStream = null;
|
BufferedReader reader = null;
|
StringBuilder response = new StringBuilder();
|
String boundary = "----WebKitFormBoundary" + UUID.randomUUID().toString().replaceAll("-", "");
|
String CRLF = "\r\n";
|
try {
|
log.info("请求地址 ->{}",httpUrl);
|
URL url = new URL(httpUrl);
|
connection = (HttpURLConnection) url.openConnection();
|
connection.setRequestMethod("POST");
|
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
|
if (authorization != null && !authorization.isEmpty()) {
|
connection.setRequestProperty("Authorization", authorization);
|
}
|
connection.setDoOutput(true);
|
log.info("入参 ->{}",maps);
|
outStream = new DataOutputStream(connection.getOutputStream());
|
for (Map.Entry<String, Object> entry : maps.entrySet()) {
|
outStream.writeBytes("--" + boundary + CRLF);
|
outStream.writeBytes("Content-Disposition: form-data; name=\"" + entry.getKey() + "\"" + CRLF);
|
outStream.writeBytes("Content-Type: text/plain; charset=UTF-8" + CRLF);
|
outStream.writeBytes(CRLF);
|
outStream.writeBytes(entry.getValue().toString() + CRLF);
|
}
|
outStream.writeBytes("--" + boundary + "--" + CRLF);
|
outStream.flush();
|
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
|
String line;
|
while ((line = reader.readLine()) != null) {
|
response.append(line);
|
}
|
log.info("返回 ->{}",response);
|
} catch (Exception e) {
|
e.printStackTrace();
|
return null;
|
} finally {
|
try {
|
if (outStream != null) outStream.close();
|
if (reader != null) reader.close();
|
} catch (IOException e) {
|
e.printStackTrace();
|
}
|
if (connection != null) {
|
connection.disconnect();
|
}
|
}
|
return response.toString();
|
}
|
|
/**
|
* 发送 post请求
|
*
|
* @param httpUrl 地址
|
* @param maps 参数
|
*/
|
public String sendHttpPost(String httpUrl, Map<String, String> maps) {
|
HttpPost httpPost = new HttpPost(httpUrl);// 创建httpPost
|
// 创建参数队列
|
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
|
for (String key : maps.keySet()) {
|
nameValuePairs.add(new BasicNameValuePair(key, maps.get(key)));
|
}
|
try {
|
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
|
} catch (Exception e) {
|
e.printStackTrace();
|
}
|
return sendHttpPost(httpPost);
|
}
|
|
|
/**
|
* 发送Post请求
|
*
|
* @param httpPost
|
* @return
|
*/
|
private String sendHttpPost(HttpPost httpPost) {
|
CloseableHttpClient httpClient = null;
|
CloseableHttpResponse response = null;
|
HttpEntity entity = null;
|
String responseContent = null;
|
try {
|
// 创建默认的httpClient实例
|
httpClient = HttpClients.createDefault();
|
httpPost.setConfig(requestConfig);
|
// 执行请求
|
long execStart = System.currentTimeMillis();
|
response = httpClient.execute(httpPost);
|
long execEnd = System.currentTimeMillis();
|
System.out.println("=================执行post请求耗时:" + (execEnd - execStart) + "ms");
|
long getStart = System.currentTimeMillis();
|
entity = response.getEntity();
|
responseContent = EntityUtils.toString(entity, "UTF-8");
|
long getEnd = System.currentTimeMillis();
|
System.out.println("=================获取响应结果耗时:" + (getEnd - getStart) + "ms");
|
} catch (Exception e) {
|
e.printStackTrace();
|
} finally {
|
try {
|
// 关闭连接,释放资源
|
if (response != null) {
|
response.close();
|
}
|
if (httpClient != null) {
|
httpClient.close();
|
}
|
} catch (IOException e) {
|
e.printStackTrace();
|
}
|
}
|
return responseContent;
|
}
|
|
/**
|
* 发送 get请求
|
*
|
* @param httpUrl
|
*/
|
public String sendHttpGet(String httpUrl) {
|
HttpGet httpGet = new HttpGet(httpUrl);// 创建get请求
|
return sendHttpGet(httpGet);
|
}
|
|
/**
|
* 发送 get请求Https
|
*
|
* @param httpUrl
|
*/
|
public String sendHttpsGet(String httpUrl) {
|
HttpGet httpGet = new HttpGet(httpUrl);// 创建get请求
|
return sendHttpsGet(httpGet);
|
}
|
|
/**
|
* 发送Get请求
|
*
|
* @param httpGet
|
* @return
|
*/
|
private String sendHttpGet(HttpGet httpGet) {
|
CloseableHttpClient httpClient = null;
|
CloseableHttpResponse response = null;
|
HttpEntity entity = null;
|
String responseContent = null;
|
try {
|
// 创建默认的httpClient实例.
|
|
|
httpClient = HttpClients.createDefault();
|
|
httpGet.setConfig(requestConfig);
|
// 执行请求
|
response = httpClient.execute(httpGet);
|
entity = response.getEntity();
|
responseContent = EntityUtils.toString(entity, "UTF-8");
|
} catch (Exception e) {
|
e.printStackTrace();
|
} finally {
|
try {
|
// 关闭连接,释放资源
|
if (response != null) {
|
response.close();
|
}
|
if (httpClient != null) {
|
httpClient.close();
|
}
|
} catch (IOException e) {
|
e.printStackTrace();
|
}
|
}
|
return responseContent;
|
}
|
|
/**
|
* 发送Get请求Https
|
*
|
* @param httpGet
|
* @return
|
*/
|
private String sendHttpsGet(HttpGet httpGet) {
|
CloseableHttpClient httpClient = null;
|
CloseableHttpResponse response = null;
|
HttpEntity entity = null;
|
String responseContent = null;
|
try {
|
// 创建默认的httpClient实例.
|
PublicSuffixMatcher publicSuffixMatcher = PublicSuffixMatcherLoader.load(new URL(httpGet.getURI().toString()));
|
DefaultHostnameVerifier hostnameVerifier = new DefaultHostnameVerifier(publicSuffixMatcher);
|
httpClient = HttpClients.custom().setSSLHostnameVerifier(hostnameVerifier).build();
|
httpGet.setConfig(requestConfig);
|
// 执行请求
|
response = httpClient.execute(httpGet);
|
entity = response.getEntity();
|
responseContent = EntityUtils.toString(entity, "UTF-8");
|
} catch (Exception e) {
|
e.printStackTrace();
|
} finally {
|
try {
|
// 关闭连接,释放资源
|
if (response != null) {
|
response.close();
|
}
|
if (httpClient != null) {
|
httpClient.close();
|
}
|
} catch (IOException e) {
|
e.printStackTrace();
|
}
|
}
|
return responseContent;
|
}
|
|
/**
|
* 发送xml数据
|
*
|
* @param url
|
* @param xmlData
|
* @return
|
* @throws ClientProtocolException
|
* @throws IOException
|
*/
|
public static HttpResponse sendXMLDataByPost(String url, String xmlData)
|
throws ClientProtocolException, IOException {
|
HttpClient httpClient = HttpClients.createDefault();
|
HttpPost httppost = new HttpPost(url);
|
StringEntity entity = new StringEntity(xmlData);
|
httppost.setEntity(entity);
|
httppost.setHeader("Content-Type", "text/xml;charset=UTF-8");
|
HttpResponse response = httpClient.execute(httppost);
|
return response;
|
}
|
|
/**
|
* 获得响应HTTP实体内容
|
*
|
* @param response
|
* @return
|
* @throws IOException
|
* @throws UnsupportedEncodingException
|
*/
|
public static String getHttpEntityContent(HttpResponse response) throws IOException, UnsupportedEncodingException {
|
HttpEntity entity = response.getEntity();
|
if (entity != null) {
|
InputStream is = entity.getContent();
|
BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
|
String line = br.readLine();
|
StringBuilder sb = new StringBuilder();
|
while (line != null) {
|
sb.append(line + "\n");
|
line = br.readLine();
|
}
|
return sb.toString();
|
}
|
return "";
|
}
|
|
|
|
public static String sendPost(String httpUrl, Map<String, Object> maps,String token) {
|
|
try {
|
// 1. 创建 URL 对象
|
URL url = new URL(httpUrl);
|
// 2. 创建 HttpURLConnection 对象
|
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
|
// 3. 设置请求方法为 POST
|
connection.setRequestMethod("POST");
|
// 4. 设置 Content-Type 头部字段
|
connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
|
//设置请求token
|
connection.setRequestProperty("Authorization",token);
|
// 6. 向服务器发送数据
|
String requestBody = JSONUtil.toJsonStr(maps);
|
log.info(httpUrl+"入参: "+requestBody);
|
// String requestBody1 = maps.toString();
|
byte[] postData = requestBody.getBytes("UTF-8");
|
connection.setDoOutput(true);
|
try (OutputStream outputStream = connection.getOutputStream()) {
|
outputStream.write(postData);
|
}
|
|
// 8. 获取响应数据
|
try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
|
String line;
|
StringBuilder response = new StringBuilder();
|
while ((line = reader.readLine()) != null) {
|
response.append(line);
|
}
|
log.info("=====================================================");
|
log.info(httpUrl+"出参");
|
log.info(response.toString());
|
connection.disconnect();
|
return response.toString();
|
}
|
} catch (IOException e) {
|
e.printStackTrace();
|
}
|
|
return null;
|
}
|
|
|
}
|