一. post表单提交:
- public static String post(String url, Map<String, String> params);
- public static String post(String url, String content, Map<String, String> headers);
- public static String post(String url, List nvps);
- public static String post(String url, List nvps, Map<String, String> headers);
- public static String post(String url, String content);
二. get请求: - public static String get(String url);
- public static String get(String url, List nvps);
- public static String get(String url, List nvps, Charset charset);
三. InputStream通过写入流的方式请求: - getForStream(String url);
- getForStream(String url, List nvps);
- public static InputStream getForStream(String url, List nvps, Charset charset);
四. 签名POST方法: - public static String post(String url, Map<String, String> params, String apiKey, String apiSecret);
具体工具类实现代码如下:
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.nio.charset.CodingErrorAction;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
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.HttpRequestBase;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.config.ConnectionConfig;
import org.apache.http.config.MessageConstraints;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.config.SocketConfig;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.entity.StringEntity;
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.util.EntityUtils;
public class HttpClientUtil {
private final static Log LOG = LogFactory.getLog(HttpClientUtil.class);
// private final static int CONNECT_TIMEOUT = 30000;
private final static int CONNECT_TIMEOUT = 6000; // in milliseconds
private final static int READ_TIMEOUT = 6000; // in milliseconds
private static PoolingHttpClientConnectionManager MANAGER = null;
private static CloseableHttpClient CLIENT = null;
static {
try {
SSLContext sslContext = SSLContexts.custom().useTLS().build();
X509TrustManager tm = new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(X509Certificate[] certs, String authType) {
}
};
sslContext.init(null, new TrustManager[] { tm }, null);
// 客户端支持TLSV1,TLSV2,TLSV3这三个版本
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
sslContext, new String[] { "TLSv1", "TLSv1.1" , "TLSv1.2" }, null,
SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER); // 客户端验证服务器身份的策略
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory> create()
.register("http", PlainConnectionSocketFactory.INSTANCE)
.register("https", sslsf).build();
MANAGER = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
// Create socket configuration
SocketConfig socketConfig = SocketConfig.custom().setTcpNoDelay(true).build();
MANAGER.setDefaultSocketConfig(socketConfig);
// Create message constraints
MessageConstraints messageConstraints = MessageConstraints.custom().setMaxHeaderCount(200).setMaxLineLength(2000).build();
// Create connection configuration
ConnectionConfig connectionConfig = ConnectionConfig.custom().setMalformedInputAction(CodingErrorAction.IGNORE)
.setUnmappableInputAction(CodingErrorAction.IGNORE).setCharset(Consts.UTF_8).setMessageConstraints(messageConstraints).build();
MANAGER.setDefaultConnectionConfig(connectionConfig);
MANAGER.setMaxTotal(200);
MANAGER.setDefaultMaxPerRoute(20);
CLIENT = HttpClients.custom().setConnectionManager(MANAGER).build();
} catch (KeyManagementException e) {
LOG.error("KeyManagementException", e);
} catch (NoSuchAlgorithmException e) {
LOG.error("NoSuchAlgorithmException", e);
}
}
/**
* 按照表单提交
* @param url
* @param params
* @return
*/
public static String post(String url, Map<String, String> params) {
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
for (Map.Entry<String, String> entry : params.entrySet()) {
nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
return post(url, nvps);
}
public static String post(String url, List<NameValuePair> nvps) {
HttpPost post = new HttpPost(url);
if (nvps != null && !nvps.isEmpty())
post.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8));
return execute(post);
}
public static String post(String url, List<NameValuePair> nvps, Map<String, String> headers) {
HttpPost post = new HttpPost(url);
if (MapUtils.isNotEmpty(headers)) {
Set<String> keySet = headers.keySet();
for (String key : keySet) {
post.setHeader(key, headers.get(key));
}
}
if (CollectionUtils.isNotEmpty(nvps))
post.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8));
return execute(post);
}
public static String post(String url, String content) {
HttpPost post = new HttpPost(url);
StringEntity entity = new StringEntity(content, Consts.UTF_8);
post.setEntity(entity);
return execute(post);
}
public static String post(String url, String content, Map<String, String> headers) {
HttpPost post = new HttpPost(url);
if (headers != null && !headers.isEmpty()) {
Set<String> keySet = headers.keySet();
for (String key : keySet) {
post.setHeader(key, headers.get(key));
}
}
StringEntity entity = new StringEntity(content, Consts.UTF_8);
post.setEntity(entity);
return execute(post);
}
/**
* 签名POST方法
* @param url
* @param params
* @param apiKey
* @param apiSecret
* @return
*/
public static String post(String url, Map<String, String> params, String apiKey, String apiSecret) {
params = sign(params, apiKey, apiSecret);
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
for (Map.Entry<String, String> entry : params.entrySet()) {
nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
return post(url, nvps);
}
public static Map<String, String> sign(Map<String, String> params, String apiKey, String apiSecret) {
if (params == null)
params = new HashMap<String, String>();
// params.put("api_key", apiKey);
String sign = SignUtil.generateSignature(params, apiSecret, "MD5");
params.put("sign", sign);
return params;
}
public static String get(String url) {
return get(url, null);
}
public static String get(String url, List<NameValuePair> nvps) {
return get(url, nvps, Consts.UTF_8);
}
public static String get(String url, List<NameValuePair> nvps, Charset charset) {
url += "?" + URLEncodedUtils.format(nvps, charset);
HttpGet get = new HttpGet(url);
return execute(get);
}
private static String execute(HttpRequestBase method) {
String result = null;
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(READ_TIMEOUT).setConnectTimeout(CONNECT_TIMEOUT)
.setConnectionRequestTimeout(CONNECT_TIMEOUT).build();
method.setConfig(requestConfig);
CloseableHttpResponse response = null;
try {
response = CLIENT.execute(method);
HttpEntity entity = response.getEntity();
if (entity != null) {
result = EntityUtils.toString(entity, "utf-8");
entity.getContent().close();
}
} catch (IOException e) {
LOG.error(e, e);
} finally {
if (response != null) {
try {
response.close();
} catch (IOException e) {
LOG.error(e, e);
}
}
method.releaseConnection();
}
return result;
}
public static InputStream getForStream(String url) {
return getForStream(url, null);
}
public static InputStream getForStream(String url, List<NameValuePair> nvps) {
return getForStream(url, nvps, Consts.UTF_8);
}
public static InputStream getForStream(String url, List<NameValuePair> nvps, Charset charset) {
if (CollectionUtils.isNotEmpty(nvps))
url += "?" + URLEncodedUtils.format(nvps, charset);
HttpGet get = new HttpGet(url);
return executeForStream(get);
}
private static InputStream executeForStream(HttpRequestBase method) {
InputStream result = null;
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(CONNECT_TIMEOUT).setConnectTimeout(CONNECT_TIMEOUT)
.setConnectionRequestTimeout(CONNECT_TIMEOUT).build();
method.setConfig(requestConfig);
CloseableHttpResponse response = null;
try {
response = CLIENT.execute(method);
HttpEntity entity = response.getEntity();
if (entity != null) {
result = entity.getContent();
}
} catch (IOException e) {
LOG.error(e, e);
} finally {
if (response != null) {
try {
response.close();
} catch (IOException e) {
LOG.error(e, e);
}
}
method.releaseConnection();
}
return result;
}
}
若哪有不足,请大家多多指教!!!