package com.httpclint.util;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.CodingErrorAction;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.apache.http.Consts;
import org.apache.http.Header;
import org.apache.http.HeaderElement;
import org.apache.http.HttpEntity;
import org.apache.http.HttpException;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpHost;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
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.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.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.ContentBody;
import org.apache.http.entity.mime.content.StringBody;
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.util.CharsetUtils;
import org.apache.http.util.EntityUtils;
/**
* 封装HttpClient
* <p>
* @author yangjian1004
* @Date Aug 5, 2014
*/
public class HttpClientWrapper {
private enum HttpMethod {
GET, POST
}
private static CloseableHttpClient client;
private List<ContentBody> contentBodies;
private List<NameValuePair> nameValuePostBodies;
private static PoolingHttpClientConnectionManager connManager = null;
public static void enabledSSL(boolean enabled) {
if (enabled) {
try {
SSLContext sslContext = SSLContexts.custom().useTLS().build();
sslContext.init(null, new TrustManager[] { new X509TrustManager() {
public void checkClientTrusted(java.security.cert.X509Certificate[] arg0, String arg1)
throws CertificateException {
}
public void checkServerTrusted(java.security.cert.X509Certificate[] arg0, String arg1)
throws CertificateException {
}
public X509Certificate[] getAcceptedIssuers() {
return null;
}
} }, null);
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder
.<ConnectionSocketFactory> create().register("http", PlainConnectionSocketFactory.INSTANCE)
.register("https", new SSLConnectionSocketFactory(sslContext)).build();
connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
SocketConfig socketConfig = SocketConfig.custom().setTcpNoDelay(true).build();
connManager.setDefaultSocketConfig(socketConfig);
MessageConstraints messageConstraints = MessageConstraints.custom().setMaxHeaderCount(200)
.setMaxLineLength(2000).build();
ConnectionConfig connectionConfig = ConnectionConfig.custom()
.setMalformedInputAction(CodingErrorAction.IGNORE)
.setUnmappableInputAction(CodingErrorAction.IGNORE).setCharset(Consts.UTF_8)
.setMessageConstraints(messageConstraints).build();
connManager.setDefaultConnectionConfig(connectionConfig);
connManager.setMaxTotal(200);
connManager.setDefaultMaxPerRoute(20);
} catch (KeyManagementException e) {
} catch (NoSuchAlgorithmException e) {
}
}
}
public HttpClientWrapper(HttpProxy proxy) {
super();
//client = HttpClientBuilder.create().build();//不使用连接池
client = this.getCloseableHttpClient(proxy);
this.contentBodies = new ArrayList<ContentBody>();
this.nameValuePostBodies = new LinkedList<NameValuePair>();
}
private CloseableHttpClient getCloseableHttpClient(HttpProxy proxy) {
if (null != proxy) {
HttpHost proxyHost = new HttpHost(proxy.getHost(), proxy.getPort());
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
if (null != proxy.getUser() && null != proxy.getPassword()) {
credentialsProvider.setCredentials(new AuthScope(proxy.getHost(), proxy.getPort()),
new UsernamePasswordCredentials(proxy.getUser(), proxy.getPassword()));
}
return HttpClients.custom().setProxy(proxyHost).setDefaultCredentialsProvider(credentialsProvider).build();
} else {
return HttpClients.custom().setConnectionManager(connManager).build();
}
}
/**
* Get方式访问URL
*
* @param url
* @return
* @throws HttpException
* @throws IOException
*/
public ResponseStatus sendRequest(String url) throws HttpException, IOException {
return this.sendRequest(url, "UTF-8", HttpMethod.GET, null);
}
/**
* Get方式访问URL
*
* @param url
* @param urlEncoding
* @return
* @throws HttpException
* @throws IOException
*/
public ResponseStatus sendRequest(String url, String urlEncoding) throws HttpException, IOException {
return this.sendRequest(url, urlEncoding, HttpMethod.GET, null);
}
/**
* POST方式发送名值对请求URL
*
* @param url
* @return
* @throws HttpException
* @throws IOException
*/
public ResponseStatus postNV(String url) throws HttpException, IOException {
return this.sendRequest(url, "UTF-8", HttpMethod.POST, null);
}
public ResponseStatus postNV(String url, String contentType) throws HttpException, IOException {
return sendRequest(url, "UTF-8", HttpMethod.POST, contentType);
}
/**
* 根据url编码,请求方式,请求URL
*
* @param urlstr
* @param urlEncoding
* @param bodyType
* @return
* @throws HttpException
* @throws IOException
*/
public ResponseStatus sendRequest(String urlstr, String urlEncoding, HttpMethod bodyType, String contentType)
throws HttpException, IOException {
if (urlstr == null)
return null;
String url = urlstr;
if (urlEncoding != null)
url = HttpClientWrapper.encodeURL(url.trim(), urlEncoding);
HttpEntity entity = null;
HttpRequestBase request = null;
CloseableHttpResponse response = null;
try {
if (HttpMethod.GET == bodyType) {
request = new HttpGet(url);
} else if (HttpMethod.POST == bodyType) {
this.parseUrl(url);
HttpPost httpPost = new HttpPost(toUrl());
List<NameValuePair> nvBodyList = this.getNVBodies();
httpPost.setEntity(new UrlEncodedFormEntity(nvBodyList, urlEncoding));
request = httpPost;
}
if (contentType != null) {
request.addHeader(HttpHeaders.CONTENT_TYPE, contentType);
}
//setTimeOut(request, timeout);
request.addHeader(HttpHeaders.USER_AGENT,
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322)");
response = client.execute(request);
- 1
- 2
- 3
- 4
- 5
- 6
前往页