<dependency>
<groupId>com.github.kevinsawicki</groupId>
<artifactId>http-request</artifactId>
<version>5.6</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
</dependency>
package com.zhichenhaixin.util;
public class HttpClientUtil {
private static final Logger log = Logger.getLogger(HttpClientUtil.class);
private static final int CONNECTION_REQUEST_TIMEOUT = 5000;
private static final int CONNECTION_TIMEOUT = 5000;
private static final int SOCKET_TIMEOUT = 10000;
private static final int MAX_CONN_TOTAL = 100;
private static final int MAX_CONN_PER_ROUTE = 50;
private static final String USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.67 Safari/537.36";
private static CloseableHttpClient httpClient = null;
private static ConnectionConfig connectionConfig = null;
private static SocketConfig socketConfig = null;
private static RequestConfig requestConfig = null;
private static BasicCookieStore cookieStore = null;
private static PoolingHttpClientConnectionManager cm;
static {
init();
}
private static void init() {
connectionConfig = ConnectionConfig.custom()
.setMalformedInputAction(CodingErrorAction.IGNORE)
.setUnmappableInputAction(CodingErrorAction.IGNORE)
.setCharset(Consts.UTF_8).build();
socketConfig = SocketConfig.custom().setTcpNoDelay(true).build();
requestConfig = RequestConfig.custom()
.setConnectionRequestTimeout(CONNECTION_REQUEST_TIMEOUT)
.setConnectTimeout(CONNECTION_TIMEOUT)
.setSocketTimeout(SOCKET_TIMEOUT)
.build();
cookieStore = new BasicCookieStore();
httpClient = HttpClients.custom()
.setMaxConnTotal(50)
.setDefaultConnectionConfig(connectionConfig)
.setDefaultSocketConfig(socketConfig)
.setDefaultRequestConfig(requestConfig)
.setDefaultCookieStore(cookieStore)
.setUserAgent(USER_AGENT)
.setMaxConnTotal(MAX_CONN_TOTAL)
.setMaxConnPerRoute(MAX_CONN_PER_ROUTE)
.setConnectionManagerShared(true)
.build();
}
public static HttpResult sendGet(String url, Cookie[] cookies) {
return sendGet(url, null, null, cookies, null);
}
public static HttpResult sendGet(String url, Map<String, String> parameters, Header[] headers, Cookie[] cookies, String charset) {
HttpResult httpResult = null;
try {
URIBuilder builder = new URIBuilder(url);
if (parameters != null && !parameters.isEmpty()) {
builder.addParameters(assemblyParameter(parameters));
}
if (charset != null) {
builder.setCharset(Charset.forName(charset));
}
URI uri = builder.build();
headers = new Header[2];
HttpGet httpGet = new HttpGet(uri);
headers[0] = new BasicHeader("Content-Type", "text/xml");
headers[1] = new BasicHeader("Accept-Ranges", "bytes");
if (headers != null) {
httpGet.setHeaders(headers);
}
if (cookies != null) {
httpGet.setHeader("cookie", assemblyCookie(cookies));
}
httpResult = httpClient.execute(httpGet, getResponseHandler());
} catch (Exception e) {
e.printStackTrace();
}
return httpResult;
}
public static HttpResult sendPostForm(String url, Map<String, String> parameters, Header[] headers, Cookie[] cookies, String charset) {
HttpResult httpResult = null;
try {
HttpPost httpPost = new HttpPost(url);
if (parameters != null && !parameters.isEmpty()) {
httpPost.setEntity(assemblyFormEntity(parameters, charset));
}
if (headers != null) {
httpPost.setHeaders(headers);
}
httpResult = httpClient.execute(httpPost, getResponseHandler());
} catch (Exception e) {
e.printStackTrace();
}
return httpResult;
}
public static HttpResult sendPostFrom(String url, String jsonData) {
HttpResult httpResult = null;
try {
HttpPost httpPost = new HttpPost(url);
httpPost.addHeader("Content-type", "application/x-www-form-urlencoded");
httpPost.addHeader("accept", "*/*");
httpPost.addHeader("connection", "Keep-Alive");
httpPost.setEntity(assemblyStringEntity(jsonData, Charset.forName("UTF-8")));
httpResult = httpClient.execute(httpPost, getResponseHandler());
} catch (IOException e) {
log.error("请求语音中心登录获取cookies失败" + e);
}
return httpResult;
}
public static HttpResult sendPostJson(String url, String jsonData) {
HttpResult httpResult = null;
try {
HttpPost httpPost = new HttpPost(url);
httpPost.addHeader("Content-type", "application/json;charset=utf-8");
httpPost.addHeader("accept", "*/*");
httpPost.addHeader("connection", "Keep-Alive");
httpPost.setEntity(assemblyStringEntity(jsonData, Charset.forName("UTF-8")));
httpResult = httpClient.execute(httpPost, getResponseHandler());
} catch (Exception e) {
log.error("send url : " + url + "; send param : " + jsonData);
e.printStackTrace();
}
return httpResult;
}
private static int i = 0;
private static void executeError(HttpResult httpResult, String url, String jsonData) {
YeaRespVo yeaRespVo = JSON.parseObject(httpResult.getStringContent(), YeaRespVo.class);
if (httpResult.getStringContent() == null || !yeaRespVo.getStatus().equals("Success") || yeaRespVo.getErrno().equals("20004")) {
if (i < 10) {
YeastarConstant.yeastarToken = YeastarUtils.login();
sendPostJson(url, jsonData);
i++;
log.info("重新登录,token 为:" + YeastarConstant.yeastarToken);
}
else {
log.error("获取token失败,请检查原因:" );
}
}
}
private static ResponseHandler<HttpResult> getResponseHandler() {
ResponseHandler<HttpResult> responseHandler = new ResponseHandler<HttpResult>() {
@Override
public HttpResult handleResponse(HttpResponse httpResponse) throws ClientProtocolException, IOException {
if (httpResponse == null) {
throw new ClientProtocolException("HttpResponse is null");
}
StatusLine statusLine = httpResponse.getStatusLine();
HttpEntity httpEntity = httpResponse.getEntity();
if (statusLine == null) {
throw new ClientProtocolException("HttpResponse contains no StatusLine");
}
if (statusLine.getStatusCode() != 200) {
throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase());
}
if (httpEntity == null) {
throw new ClientProtocolException("HttpResponse contains no HttpEntity");
}
HttpResult httpResult = new HttpResult();
httpResult.setStatusCode(statusLine.getStatusCode());
ContentType contentType = ContentType.getOrDefault(httpEntity);
httpResult.setContentType(contentType.toString());
boolean isTextType = isTextType(contentType);
httpResult.setTextType(isTextType);
if (isTextType) {
httpResult.setStringContent(EntityUtils.toString(httpEntity));
} else {
httpResult.setByteArrayContent(EntityUtils.toByteArray(httpEntity));
}
httpResult.setCookies(cookieStore.getCookies());
httpResult.setHeaders(httpResponse.getAllHeaders());
return httpResult;
}
};
return responseHandler;
}
private static List<NameValuePair> assemblyParameter(Map<String, String> parameters) {
List<NameValuePair> allParameter = new ArrayList<>();
if (parameters != null && !parameters.isEmpty()) {
for (String name : parameters.keySet()) {
NameValuePair parameter = new BasicNameValuePair(name, parameters.get(name));
allParameter.add(parameter);
}
}
return allParameter;
}
private static UrlEncodedFormEntity assemblyFormEntity(Map<String, String> parameters, String charset) {
List<NameValuePair> formParameters = assemblyParameter(parameters);
UrlEncodedFormEntity formEntity = null;
try {
if (charset != null) {
formEntity = new UrlEncodedFormEntity(formParameters, charset);
} else {
formEntity = new UrlEncodedFormEntity(formParameters);
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return formEntity;
}
private static StringEntity assemblyStringEntity(String jsonData, Charset charset) {
if (jsonData == null || jsonData.equals("")) {
jsonData = "{}";
}
StringEntity stringEntity = new StringEntity(jsonData, ContentType.APPLICATION_JSON);
if (charset != null) {
stringEntity.setContentEncoding("UTF-8");
}
return stringEntity;
}
private static String assemblyCookie(Cookie[] cookies) {
StringBuilder sb = new StringBuilder();
if (cookies != null) {
for (Cookie cookie : cookies) {
sb.append(cookie.getName()).append("=").append(cookie.getValue()).append(";");
}
}
return sb.toString();
}
private static boolean isTextType(ContentType contentType) {
if (contentType == null) {
throw new RuntimeException("ContentType is null");
}
if (contentType.getMimeType().startsWith("text")) {
return true;
} else if (contentType.getMimeType().startsWith("image")) {
return false;
} else if (contentType.getMimeType().startsWith("application")) {
if (contentType.getMimeType().contains("json") || contentType.getMimeType().contains("xml")) {
return true;
} else {
return false;
}
} else if (contentType.getMimeType().startsWith("multipart")) {
return false;
} else {
return true;
}
}
}