pars-nft/src/main/java/com/szxgl/nft/utils/HttpClientUtil.java
2022-02-25 17:12:38 +08:00

235 lines
8.5 KiB
Java

package com.szxgl.nft.utils;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.CookieSpecs;
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.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
/**
* HttpClients 请求工具类
*
* @author Leon
* @datetime 2018年8月13日 下午4:42:17
*/
public class HttpClientUtil {
private static Logger logger = LoggerFactory.getLogger(HttpClientUtil.class);
private static final CloseableHttpClient httpClient;
static {
RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.IGNORE_COOKIES).setConnectTimeout(5000).setSocketTimeout(5000).build();
httpClient = HttpClientBuilder.create().setDefaultRequestConfig(globalConfig).build();
}
public static JSONObject doPost(String url, JSONObject json) {
// CloseableHttpClient client = HttpClients.custom().setDefaultRequestConfig(globalConfig).build();
HttpPost httpPost = new HttpPost(url);
JSONObject response = null;
CloseableHttpResponse res = null;
try {
// 设置请求的header
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
httpPost.setHeader("Accept", "application/json;charset=utf-8");
//--------------------设置不使用长连接-----------------------------
httpPost.setHeader(HttpHeaders.CONNECTION, "close");
StringEntity s = new StringEntity(formatPostData(json), "UTF-8");
//s.setContentEncoding("UTF-8");
// s.setContentType("x-www-form-urlencoded");//发送json数据需要设置contentType
httpPost.setEntity(s);
res = httpClient.execute(httpPost);
int statusCode = res.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
logger.info("请求接口返回状态吗, getStatusCode=" + statusCode + ", getReasonPhrase=" + res.getStatusLine().getReasonPhrase());
httpPost.abort();
throw new Exception("HttpClient,error status code :" + statusCode);
}
HttpEntity entity = res.getEntity();
if (entity != null) {
String result = EntityUtils.toString(entity, "UTF-8");
response = JSONObject.parseObject(result);
}
} catch (Exception e) {
logger.error("HTTP-POST请求出错, URL=" + url + "请求数据:" + json, e);
} finally {
httpPost.releaseConnection();
if (res != null) {
try {
EntityUtils.consume(res.getEntity());
} catch (IOException e) {
}
try {
res.close();
} catch (IOException e) {
}
//----------------------关闭-----------------------------
if (httpPost != null) {
httpPost.releaseConnection();
}
}
}
return response;
}
public static String doPost(String url, Map<String, String> params, String charset) {
if (StringUtils.isBlank(url)) {
return null;
}
if (StringUtils.isBlank(charset)) {
charset = "utf-8";
}
HttpPost httpPost = null;
try {
List<NameValuePair> pairs = null;
if (params != null && !params.isEmpty()) {
pairs = new ArrayList<NameValuePair>(params.size());
for (Entry<String, String> entry : params.entrySet()) {
String value = entry.getValue();
if (value != null) {
pairs.add(new BasicNameValuePair(entry.getKey(), value));
}
}
}
httpPost = new HttpPost(url);
if (pairs != null && pairs.size() > 0) {
httpPost.setEntity(new UrlEncodedFormEntity(pairs, charset));
}
CloseableHttpResponse response = httpClient.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != 200) {
httpPost.abort();
throw new RuntimeException("HttpClient,error status code :" + statusCode);
}
HttpEntity entity = response.getEntity();
String result = null;
if (entity != null) {
result = EntityUtils.toString(entity, charset);
}
EntityUtils.consume(entity);
response.close();
// System.out.println("------------"+result);
return result;
} catch (Exception e) {
if (httpPost != null) {
httpPost.abort();
}
e.printStackTrace();
}
return null;
}
/**
* GET请求
*
* @param url
* @return
*/
public static JSONObject doGet(String url) {
HttpGet httpGet = new HttpGet(url);
CloseableHttpResponse res = null;
JSONObject response = null;
try {
// 设置请求的header
httpGet.setHeader("Content-Type", "application/json;charset=utf-8");
httpGet.setHeader("Accept", "application/json;charset=utf-8");
res = httpClient.execute(httpGet);
int statusCode = res.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
logger.info("请求接口返回状态码, getStatusCode=" + statusCode + ", getReasonPhrase=" + res.getStatusLine().getReasonPhrase());
httpGet.abort();
throw new Exception("HttpClient,error status code :" + statusCode);
}
HttpEntity entity = res.getEntity();
if (entity != null) {
String result = EntityUtils.toString(entity, "UTF-8");
response = JSONObject.parseObject(result);
}
} catch (Exception e) {
logger.error("HTTP-GET请求出错, URL=" + url, e);
} finally {
httpGet.releaseConnection();
if (res != null) {
try {
EntityUtils.consume(res.getEntity());
} catch (IOException e) {
}
try {
res.close();
} catch (IOException e) {
}
}
}
return response;
}
protected static String formatPostData(JSONObject json) {
String result = null;
try {
JSONObject jsonObject = json;
if (jsonObject != null) {
result = "?";
for (Entry<String, Object> entry : jsonObject.entrySet()) {
if (StringUtils.isEmpty(result)) {
result = entry.getKey() + "=" + entry.getValue();
} else {
result += "&" + entry.getKey() + "=" + entry.getValue();
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
protected static String formatPostData(String strdata) {
String result = strdata;
try {
JSONObject jsonObject = JSONObject.parseObject(strdata);
if (jsonObject != null) {
result = "";
for (Entry<String, Object> entry : jsonObject.entrySet()) {
if (StringUtils.isEmpty(result)) {
result = entry.getKey() + "=" + entry.getValue();
} else {
result += "&" + entry.getKey() + "=" + entry.getValue();
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
}