package com.stylefeng.guns.core.util;
|
|
import com.aliyun.oss.ServiceException;
|
import org.apache.http.Consts;
|
import org.apache.http.HttpResponse;
|
import org.apache.http.HttpStatus;
|
import org.apache.http.client.ClientProtocolException;
|
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.client.methods.HttpUriRequest;
|
import org.apache.http.client.protocol.HttpClientContext;
|
import org.apache.http.client.utils.URIBuilder;
|
import org.apache.http.entity.StringEntity;
|
import org.apache.http.impl.client.CloseableHttpClient;
|
import org.apache.http.impl.client.HttpClientBuilder;
|
import org.apache.http.impl.client.HttpClients;
|
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
|
import org.apache.http.message.BasicNameValuePair;
|
import org.apache.http.util.EntityUtils;
|
import org.apache.http.util.TextUtils;
|
|
import java.io.BufferedReader;
|
import java.io.IOException;
|
import java.io.InputStreamReader;
|
import java.io.OutputStream;
|
import java.net.HttpURLConnection;
|
import java.net.URI;
|
import java.net.URISyntaxException;
|
import java.net.URL;
|
import java.nio.charset.StandardCharsets;
|
import java.util.ArrayList;
|
import java.util.Iterator;
|
import java.util.List;
|
import java.util.Map;
|
import java.util.stream.Collectors;
|
|
public class HttpUtil {
|
|
//请求超时时间
|
private final static Integer TIME_OUT = 8 * 1000;
|
//http连接池
|
private static volatile PoolingHttpClientConnectionManager poolingHttpClientConnectionManager;
|
//请求配置
|
private static RequestConfig requestConfig;
|
|
public static PoolingHttpClientConnectionManager getPoolingHttpClientConnectionManager() {
|
if (poolingHttpClientConnectionManager == null) {
|
synchronized (HttpUtils.class) {
|
if (poolingHttpClientConnectionManager == null) {
|
poolingHttpClientConnectionManager = new PoolingHttpClientConnectionManager();
|
//连接池最大连接数
|
poolingHttpClientConnectionManager.setMaxTotal(1024);
|
//每个路由最大连接数
|
poolingHttpClientConnectionManager.setDefaultMaxPerRoute(32);
|
|
//配置请求的超时设置
|
requestConfig =
|
RequestConfig.custom().setConnectionRequestTimeout(TIME_OUT).setConnectTimeout(TIME_OUT).setSocketTimeout(TIME_OUT).build();
|
}
|
}
|
}
|
return poolingHttpClientConnectionManager;
|
}
|
|
public static CloseableHttpClient getHttpClient() {
|
return HttpClients.custom().setConnectionManager(getPoolingHttpClientConnectionManager()).setDefaultRequestConfig(requestConfig).build();
|
}
|
|
/**
|
* 请求发送执行
|
*
|
* @param httpMethd
|
* @return
|
*/
|
public static String registRequest(HttpUriRequest httpMethd) {
|
CloseableHttpClient httpClient = getHttpClient();
|
try (CloseableHttpResponse httpResponse = httpClient.execute(httpMethd, HttpClientContext.create())) {
|
int statusCode = httpResponse.getStatusLine().getStatusCode();
|
if (httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
|
httpMethd.abort();
|
}
|
String response = EntityUtils.toString(httpResponse.getEntity(), Consts.UTF_8);
|
return response;
|
} catch (Exception e) {
|
throw new RuntimeException("请求失败", e);
|
}
|
}
|
|
public static List<BasicNameValuePair> toPairs(Map<String, Object> params) {
|
List<BasicNameValuePair> pairs = new ArrayList<>(params.size());
|
if (params != null && !params.isEmpty()) {
|
pairs = params.entrySet().stream().map(entry -> new BasicNameValuePair(entry.getKey(),
|
entry.getValue().toString())).collect(Collectors.toList());
|
}
|
return pairs;
|
}
|
|
/**
|
* get url请求
|
*
|
* @param url
|
* @return
|
*/
|
public static String get(String url) {
|
HttpGet request = new HttpGet();
|
try {
|
request.setURI(new URI(url));
|
return registRequest(request);
|
} catch (Exception e) {
|
e.printStackTrace();
|
}
|
return null;
|
}
|
|
/***
|
* get请求(带参数)
|
* @param url
|
* @return String
|
*/
|
public static String getReq(String url, Map<String, String> params) {
|
String result = null;
|
try {
|
URIBuilder uriBuilder = new URIBuilder(url);
|
Iterator maplist = params.entrySet().iterator();
|
while (maplist.hasNext()) {
|
Map.Entry<String, String> map = (Map.Entry<String, String>) maplist.next();
|
uriBuilder.addParameter(map.getKey(), map.getValue());
|
}
|
CloseableHttpClient client = HttpClientBuilder.create().build();
|
HttpGet get = new HttpGet(uriBuilder.build());
|
get.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36");
|
HttpResponse response = client.execute(get);
|
result = EntityUtils.toString(response.getEntity(), "UTF-8");
|
|
} catch (URISyntaxException e) {
|
e.printStackTrace();
|
} catch (ClientProtocolException e) {
|
e.printStackTrace();
|
} catch (IOException e) {
|
e.printStackTrace();
|
}
|
return result;
|
}
|
|
/***
|
* get请求(带参数)
|
* @param url
|
* @return String
|
*/
|
public static String postReq(String url, Map<String, Object> params,String token) {
|
String result = null;
|
try {
|
URIBuilder uriBuilder = new URIBuilder(url);
|
Iterator maplist = params.entrySet().iterator();
|
while (maplist.hasNext()) {
|
Map.Entry<String, Object> map = (Map.Entry<String, Object>) maplist.next();
|
uriBuilder.addParameter(map.getKey(), String.valueOf(map.getValue()));
|
}
|
CloseableHttpClient client = HttpClientBuilder.create().build();
|
HttpPost post = new HttpPost(uriBuilder.build());
|
post.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36");
|
post.addHeader("Content-type", "application/json");
|
post.addHeader("Accept", "application/json");
|
post.addHeader("Authorization", token);
|
HttpResponse response = client.execute(post);
|
result = EntityUtils.toString(response.getEntity(), "UTF-8");
|
|
} catch (URISyntaxException e) {
|
e.printStackTrace();
|
} catch (ClientProtocolException e) {
|
e.printStackTrace();
|
} catch (IOException e) {
|
e.printStackTrace();
|
}
|
return result;
|
}
|
|
/**
|
* PSOT URL方式提交
|
*
|
* @param url 请求url
|
* @param params 请求参数
|
* @return
|
*/
|
public static String postFromUrl(String url, Map<String, Object> params) {
|
HttpPost request = new HttpPost(url);
|
request.setEntity(new UrlEncodedFormEntity(toPairs(params), Consts.UTF_8));
|
try {
|
return registRequest(request);
|
} catch (Exception e) {
|
e.printStackTrace();
|
}
|
return null;
|
}
|
|
/**
|
* PSOT JSON方式提交
|
*
|
* @param url 请求url
|
* @param params json串
|
* @return
|
*/
|
public static String postFromJson(String url, String params,String token) {
|
HttpPost request = new HttpPost(url);
|
request.setHeader("Content-type", "application/json");
|
request.setHeader("Accept", "application/json");
|
request.setHeader("Authorization", token);
|
RequestConfig requestConfig = RequestConfig.custom()
|
.setSocketTimeout(8000)
|
.setConnectTimeout(6000)
|
.build();
|
request.setConfig(requestConfig);
|
StringEntity entity = new StringEntity(params, StandardCharsets.UTF_8);
|
entity.setContentType("application/json");
|
request.setEntity(entity);
|
try {
|
return registRequest(request);
|
} catch (Exception e) {
|
e.printStackTrace();
|
}
|
return null;
|
}
|
|
/**
|
* PSOT JSON方式提交
|
*
|
* @param url 请求url
|
* @param params json串
|
* @return
|
*/
|
public static String postFromJson(String url, String params) {
|
HttpPost request = new HttpPost(url);
|
request.setHeader("Content-type", "application/json");
|
request.setHeader("Accept", "application/json");
|
RequestConfig requestConfig = RequestConfig.custom()
|
.setSocketTimeout(8000)
|
.setConnectTimeout(6000)
|
.build();
|
request.setConfig(requestConfig);
|
StringEntity entity = new StringEntity(params, StandardCharsets.UTF_8);
|
entity.setContentType("application/json");
|
request.setEntity(entity);
|
try {
|
return registRequest(request);
|
} catch (Exception e) {
|
e.printStackTrace();
|
}
|
return null;
|
}
|
|
|
/**
|
* post请求带token
|
* @param strURL
|
* @param params
|
* @param token
|
* @return
|
*/
|
public static String post(String strURL, String params, String token) {
|
String result = "";
|
BufferedReader reader = null;
|
try {
|
System.out.println(strURL);
|
System.out.println(params);
|
URL url = new URL(strURL);// 创建连接
|
HttpURLConnection connection = (HttpURLConnection) url
|
.openConnection();
|
connection.setDoOutput(true);
|
connection.setDoInput(true);
|
connection.setUseCaches(false);
|
connection.setInstanceFollowRedirects(true);
|
connection.setRequestMethod("POST"); // 设置请求方式
|
connection.setRequestProperty("Accept", "application/json;charset=utf-8"); // 设置接收数据的格式
|
connection.setRequestProperty("Content-Type", "application/json;charset=utf-8"); // 设置发送数据的格式
|
connection.setRequestProperty("Authorization", token); // 设置token
|
connection.connect();
|
if (params != null && !TextUtils.isEmpty(params)) {
|
byte[] writebytes = params.getBytes();
|
// 设置文件长度
|
// connection.setRequestProperty("Content-Length", String.valueOf(writebytes.length));
|
OutputStream outwritestream = connection.getOutputStream();
|
outwritestream.write(params.getBytes());
|
outwritestream.flush();
|
outwritestream.close();
|
// Log.d("hlhupload", "doJsonPost: conn"+connection.getResponseCode());
|
}
|
if (connection.getResponseCode() == 200) {
|
reader = new BufferedReader(
|
new InputStreamReader(connection.getInputStream()));
|
result = reader.readLine();
|
} else {
|
throw new ServiceException(connection.getResponseMessage());
|
}
|
} catch (Exception e) {
|
throw new ServiceException("http的post请求异常!" + e.getMessage());
|
} finally {
|
if (reader != null) {
|
try {
|
reader.close();
|
} catch (IOException e) {
|
e.printStackTrace();
|
}
|
}
|
}
|
return result;
|
}
|
|
/**
|
* post请求
|
* @param strURL
|
* @param params
|
* @return
|
*/
|
public static String post(String strURL, String params) {
|
String result = "";
|
BufferedReader reader = null;
|
try {
|
URL url = new URL(strURL);// 创建连接
|
HttpURLConnection connection = (HttpURLConnection) url
|
.openConnection();
|
connection.setDoOutput(true);
|
connection.setDoInput(true);
|
connection.setUseCaches(false);
|
connection.setInstanceFollowRedirects(true);
|
connection.setRequestMethod("POST"); // 设置请求方式
|
connection.setRequestProperty("Accept", "application/json;charset=utf-8"); // 设置接收数据的格式
|
connection.setRequestProperty("Content-Type", "application/json;charset=utf-8"); // 设置发送数据的格式
|
connection.connect();
|
if (params != null && !TextUtils.isEmpty(params)) {
|
byte[] writebytes = params.getBytes();
|
// 设置文件长度
|
// connection.setRequestProperty("Content-Length", String.valueOf(writebytes.length));
|
OutputStream outwritestream = connection.getOutputStream();
|
outwritestream.write(params.getBytes());
|
outwritestream.flush();
|
outwritestream.close();
|
// Log.d("hlhupload", "doJsonPost: conn"+connection.getResponseCode());
|
}
|
if (connection.getResponseCode() == 200) {
|
reader = new BufferedReader(
|
new InputStreamReader(connection.getInputStream()));
|
result = reader.readLine();
|
} else {
|
throw new ServiceException(connection.getResponseMessage());
|
}
|
} catch (Exception e) {
|
throw new ServiceException("http的post请求异常!" + e.getMessage());
|
} finally {
|
if (reader != null) {
|
try {
|
reader.close();
|
} catch (IOException e) {
|
e.printStackTrace();
|
}
|
}
|
}
|
return result;
|
}
|
}
|