httpUtils 工具类,专门用于java端发送http请求的,可以支持get, post ,put json ,get post put form 格式的请求
允许添加不带用户名密码的代理,和带用户名密码的代理。
package com.xxxx;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.NameValuePair;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.*;
public class HttpUtils {
private static final Logger logger = LoggerFactory.getLogger(HttpUtils.class);
private static final String DEFAULT_UTF8_ENCODING = "UTF-8";
private static final String APPLICATION_JSON = "application/json";
private static final CloseableHttpClient HC;
public static final int CONNECT_TIMEOUT = 60 * 1000;
private static final RequestConfig defaultRc = RequestConfig.custom()
.setConnectionRequestTimeout(60 * 1000)
.setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(CONNECT_TIMEOUT).build();
static {
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
cm.setMaxTotal(1024);
cm.setDefaultMaxPerRoute(128);
// Connection timeout is the timeout until a connection with the server is established.
// ConnectionRequestTimeout used when requesting a connection from the connection manager.
HC = HttpClients.custom().setConnectionManager(cm).setDefaultRequestConfig(defaultRc).build();
}
/**
*
* @param requestUrl 访问地址
* @param method http 访问方式
* @param requestParams 请求参数
* @param headers 请求头
* @param proxyHost 代理ip 不带http://
* @param proxyPort 端口
* @param proxyScheme http/https
* @param proxyUsername 代理用户名
* @param proxyPassword 代理密码
* @param connectTimeoutMillis
* @param socketReadTimeoutMillis
* @return
* @throws Exception
*/
public static String requestFormHttp(String requestUrl, String method, Map requestParams,
Map headers, String proxyHost, Integer proxyPort,
String proxyScheme, String proxyUsername, String proxyPassword,
int connectTimeoutMillis, int socketReadTimeoutMillis) throws Exception {
HttpRequestBase httpUriRequest;
List params = new ArrayList<>();
if (requestParams != null) {
Iterator> it = requestParams.entrySet().iterator();
while (it.hasNext()) {
Map.Entry en = it.next();
String key = en.getKey();
Object value = en.getValue();
if (value != null) {
params.add(new BasicNameValuePair(key, value.toString()));
}
}
}
if ("GET".equalsIgnoreCase(method)) {
httpUriRequest = new HttpGet(requestUrl);
} else if ("POST".equalsIgnoreCase(method)) {
httpUriRequest = new HttpPost(requestUrl);
if(!isEmpty(params)) {
((HttpPost) httpUriRequest).setEntity(new UrlEncodedFormEntity(params, DEFAULT_UTF8_ENCODING));
}
} else if ("PUT".equalsIgnoreCase(method)) {
httpUriRequest = new HttpPut(requestUrl);
if(!isEmpty(params)) {
((HttpPut) httpUriRequest).setEntity(new UrlEncodedFormEntity(params, DEFAULT_UTF8_ENCODING));
}
} else if ("DELETE".equalsIgnoreCase(method)) {
httpUriRequest = new HttpDelete(requestUrl);
} else {
throw new RuntimeException("method " + method + " is not support");
}
//附加参数中的header到http request中
if (headers != null) {
Iterator> itHeaders = headers.entrySet().iterator();
while (itHeaders.hasNext()) {
Map.Entry en = itHeaders.next();
String key = en.getKey();
Object value = en.getValue();
if (value != null) {
httpUriRequest.setHeader(key, value.toString());
}
}
}
return requestByProxy(httpUriRequest, proxyHost, proxyPort, proxyScheme, proxyUsername, proxyPassword, connectTimeoutMillis, socketReadTimeoutMillis);
}
private static String requestByProxy(HttpRequestBase httpUriRequest, String proxyHost, Integer proxyPort,
String proxyScheme, String proxyUsername, String proxyPassword,
int connectTimeoutMillis, int socketReadTimeoutMillis) {
String result = null;
HttpClientContext context = HttpClientContext.create();
//把代理设置到请求配置
RequestConfig defaultRequestConfig = buildRequestConfig(proxyHost, proxyPort, proxyScheme,
connectTimeoutMillis, socketReadTimeoutMillis);
if (StringUtils.isNotBlank(proxyUsername)) {
HttpHost proxy = new HttpHost(proxyHost, proxyPort, proxyScheme);
// 设置认证
CredentialsProvider provider = new BasicCredentialsProvider();
provider.setCredentials(new AuthScope(proxy), new UsernamePasswordCredentials(proxyUsername,
proxyPassword));
context.setCredentialsProvider(provider);
}
httpUriRequest.setConfig(defaultRequestConfig);
HttpEntity httpEntity = null;
try (CloseableHttpResponse httpResponse = HC.execute(httpUriRequest, context)) {
/** HttpResponse */
httpEntity = httpResponse.getEntity();
result = httpEntity != null ? EntityUtils.toString(httpEntity, DEFAULT_UTF8_ENCODING) : null;
} catch (Exception e) {
try {
EntityUtils.consume(httpEntity);
} catch (IOException ioException) {
logger.error("http entity error", e);
}
throw new RuntimeException(e);
}
return result;
}
private static RequestConfig buildRequestConfig(String proxyHost, Integer proxyPort, String proxyScheme, int connectTimeoutMillis, int socketReadTimeoutMillis) {
if (StringUtils.isNotBlank(proxyHost)) {
HttpHost proxy = new HttpHost(proxyHost, proxyPort, proxyScheme);
return RequestConfig.custom()
.setConnectionRequestTimeout(connectTimeoutMillis)
.setConnectTimeout(connectTimeoutMillis).setSocketTimeout(socketReadTimeoutMillis)
.setProxy(proxy)
.build();
} else {
return RequestConfig.custom()
.setConnectionRequestTimeout(connectTimeoutMillis)
.setConnectTimeout(connectTimeoutMillis).setSocketTimeout(socketReadTimeoutMillis)
.build();
}
}
/**
* @param requestUrl 请求地址
* @param method 请求方法
* @param requestJson 请求参数
* @param headers 请求头
* @param proxyHost 代理地址
* @param proxyPort 代理端口
* @param proxyScheme http/https
* @param proxyUsername 代理用户名
* @param proxyPassword 代理秘密
* @param connectTimeoutMillis
* @param socketReadTimeoutMillis
* @return
* @throws Exception
*/
public static String requestJsonHttp(String requestUrl, String method, String requestJson,
Map headers, String proxyHost, Integer proxyPort,
String proxyScheme, String proxyUsername, String proxyPassword,
int connectTimeoutMillis, int socketReadTimeoutMillis) throws Exception {
HttpRequestBase httpUriRequest;
if ("GET".equalsIgnoreCase(method)) {
httpUriRequest = new HttpGet(requestUrl);
} else if ("POST".equalsIgnoreCase(method)) {
httpUriRequest = new HttpPost(requestUrl);
if (StringUtils.isNotBlank(requestJson)) {
((HttpPost) httpUriRequest).setEntity(new StringEntity(requestJson, StandardCharsets.UTF_8));
}
} else if ("PUT".equalsIgnoreCase(method)) {
httpUriRequest = new HttpPut(requestUrl);
if (StringUtils.isNotBlank(requestJson)) {
((HttpPut) httpUriRequest).setEntity(new StringEntity(requestJson, StandardCharsets.UTF_8));
}
} else {
throw new RuntimeException("method " + method + " is not support");
}
httpUriRequest.addHeader(HTTP.CONTENT_TYPE, APPLICATION_JSON);
//如果有特殊的Header
if (!isEmpty(headers)) {
headers.forEach(httpUriRequest::addHeader);
}
return requestByProxy(httpUriRequest, proxyHost, proxyPort, proxyScheme, proxyUsername, proxyPassword, connectTimeoutMillis, socketReadTimeoutMillis);
}
private static boolean isEmpty(Collection c) {
return c == null || c.size() == 0;
}
private static boolean isEmpty(Map m) {
return m == null || m.size() == 0;
}
}