代码是对apache httpclient的简单封装,支持用户登录,调用方式如下
import org.junit.Test;
/**
* @author niuhaipeng
*
* @date 2015年12月24日
*/
public class HttpClientTest {
@Test
public void testGet2String() {
SimpleHttpClient client = new SimpleHttpClient();
String url = "http://niuhp.com";
while (true) {
String content = client.doGet2String(url);
System.out.println(content);
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
实现代码
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.AuthSchemes;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.config.RequestConfig.Builder;
import org.apache.http.client.entity.UrlEncodedFormEntity;
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.methods.HttpUriRequest;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.ContentType;
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 com.niuhp.toolbox.logadapter.LogX;
import com.niuhp.toolbox.util.IoUtil;
/**
* @author niuhaipeng
*
* @date 2015年12月17日
*/
public class SimpleHttpClient {
private HttpClient httpClient;
private Object lockObj = new Object();
private int connectionRequestTimeout = 10000;
private int connectTimeout = 10000;
private int defaultMaxPerRoute = 20;
private int maxTotal = 100;
/**
* 请求自动关闭时间,防止调用者长期持有请求
*/
private long autoCloseTimeout = 3000;
private final ExecutorService executorService = Executors.newFixedThreadPool(50);
private void checkInit(boolean https) {
if (httpClient != null) {
return;
}
synchronized (lockObj) {
if (httpClient != null) {
return;
}
Builder builder = RequestConfig.custom();
builder.setCookieSpec(CookieSpecs.STANDARD_STRICT);
builder.setConnectionRequestTimeout(connectionRequestTimeout);
builder.setConnectTimeout(connectTimeout);
if (https) {
builder.setExpectContinueEnabled(true);
Collection<String> targetPreferredAuthSchemes = Arrays.asList(AuthSchemes.NTLM, AuthSchemes.DIGEST);
builder.setTargetPreferredAuthSchemes(targetPreferredAuthSchemes);
Collection<String> proxyPreferredAuthSchemes = Arrays.asList(AuthSchemes.BASIC);
builder.setProxyPreferredAuthSchemes(proxyPreferredAuthSchemes);
}
RequestConfig config = builder.build();
HttpClientBuilder httpClientBuilder = HttpClients.custom();
httpClientBuilder.setDefaultRequestConfig(config);
if (https) {
RegistryBuilder<ConnectionSocketFactory> registryBuilder = RegistryBuilder.create();
registryBuilder.register("http", PlainConnectionSocketFactory.INSTANCE);
TrustManager trustManager = new CustomizedX509TrustManager();
try {
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, new TrustManager[] { trustManager }, null);
ConnectionSocketFactory connectionSocketFactory = new SSLConnectionSocketFactory(context,
NoopHostnameVerifier.INSTANCE);
registryBuilder.register("https", connectionSocketFactory);
} catch (Exception e) {
LogX.getLogX(getClass()).error("register connectionSocketFactory error", e);
}
Registry<ConnectionSocketFactory> registry = registryBuilder.build();
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(registry);
connManager.setMaxTotal(maxTotal);
connManager.setDefaultMaxPerRoute(defaultMaxPerRoute);
httpClientBuilder.setConnectionManager(connManager);
}
httpClient = httpClientBuilder.build();
}
}
public String doGet2String(String url) {
return doGet2String(url, null);
}
public String doGet2String(String url, Map<String, String> paraMap) {
HttpResponse reponse = doGet(url, paraMap);
return getContent(reponse);
}
public HttpResponse doGet(String url, Map<String, String> paraMap) {
StringBuilder urlBuilder = new StringBuilder();
urlBuilder.append(url);
if (paraMap != null && !paraMap.isEmpty()) {
urlBuilder.append("?");
Set<String> keys = paraMap.keySet();
Iterator<String> it = keys.iterator();
String key = it.next();
urlBuilder.append(key).append("=").append(paraMap.get(key));
while (it.hasNext()) {
key = it.next();
urlBuilder.append("&").append(key).append("=").append(paraMap.get(key));
}
}
return doGet(urlBuilder.toString());
}
public HttpResponse doGet(String url) {
boolean https = url != null && url.startsWith("https");
checkInit(https);
HttpGet get = new HttpGet(url);
return doRequest(httpClient, get);
}
public String doPost2String(String url) {
return doPost2String(url, null);
}
public String doPost2String(String url, Map<String, String> paraMap) {
HttpResponse response = doPost(url, paraMap);
return getContent(response);
}
public HttpResponse doPost(String url) {
return doPost(url, null);
}
public HttpResponse doPost(String url, Map<String, String> paraMap) {
boolean https = url != null && url.startsWith("https");
checkInit(https);
HttpPost post = new HttpPost(url);
List<NameValuePair> values = toValues(paraMap);
if (values != null && !values.isEmpty()) {
HttpEntity entity = new UrlEncodedFormEntity(values, Consts.UTF_8);
post.setEntity(entity);
}
return doRequest(httpClient, post);
}
private void autoClose(HttpUriRequest request, HttpResponse reponse) {
Runnable runnable = new Runnable() {
@Override
public void run() {
try {
Thread.sleep(autoCloseTimeout);
} catch (InterruptedException e) {
LogX.getLogX(getClass()).error("sleep error", e);
}
if (request instanceof HttpRequestBase) {
HttpRequestBase httpRequestBase = (HttpRequestBase) request;
httpRequestBase.releaseConnection();
}
IoUtil.closeHttpResponse(reponse);
LogX.getLogX(getClass()).info(String.format("autoClose request[%s] and reponse[%s]", request, reponse));
}
};
executorService.execute(runnable);
}
private HttpResponse doRequest(HttpClient httpClient, HttpUriRequest httpRequest) {
synchronized (httpClient) {
try {
HttpResponse response = httpClient.execute(httpRequest);
autoClose(httpRequest, response);
return response;
} catch (Exception e) {
LogX.getLogX(getClass()).error("execute error", e);
}
}
return null;
}
public void closeHttpClient() {
IoUtil.closeHttpClient(httpClient);
}
private static List<NameValuePair> toValues(Map<String, String> paraMap) {
if (paraMap == null) {
return null;
}
List<NameValuePair> values = new ArrayList<NameValuePair>(paraMap.size());
Set<String> keys = paraMap.keySet();
for (String key : keys) {
NameValuePair pair = new BasicNameValuePair(key, paraMap.get(key));
values.add(pair);
}
return values;
}
private String getContent(HttpResponse response) {
if (response == null) {
return null;
}
HttpEntity httpEntity = response.getEntity();
if (httpEntity == null) {
return null;
}
String content = null;
try {
Charset charset = ContentType.getOrDefault(httpEntity).getCharset();
content = EntityUtils.toString(httpEntity, charset);
} catch (IOException e) {
LogX.getLogX(getClass()).error("getContent error", e);
} finally {
IoUtil.closeHttpResponse(response);
}
return content;
}
public int getConnectionRequestTimeout() {
return connectionRequestTimeout;
}
public void setConnectionRequestTimeout(int connectionRequestTimeout) {
this.connectionRequestTimeout = connectionRequestTimeout;
}
public int getConnectTimeout() {
return connectTimeout;
}
public void setConnectTimeout(int connectTimeout) {
this.connectTimeout = connectTimeout;
}
public int getDefaultMaxPerRoute() {
return defaultMaxPerRoute;
}
public void setDefaultMaxPerRoute(int defaultMaxPerRoute) {
this.defaultMaxPerRoute = defaultMaxPerRoute;
}
public int getMaxTotal() {
return maxTotal;
}
public void setMaxTotal(int maxTotal) {
this.maxTotal = maxTotal;
}
public long getAutoCloseTimeout() {
return autoCloseTimeout;
}
public void setAutoCloseTimeout(long autoCloseTimeout) {
if (autoCloseTimeout <= 0 || autoCloseTimeout > 5000) {
LogX.getLogX(getClass()).warn(String.format("autoCloseTimeout must be from %s to %s", 0, 5000));
return;
}
this.autoCloseTimeout = autoCloseTimeout;
}
}
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.X509TrustManager;
/**
* @author niuhaipeng
*
* @date 2015年12月17日
*/
public class CustomizedX509TrustManager implements X509TrustManager {
@Override
public void checkClientTrusted(X509Certificate[] arg0, String arg1)
throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] arg0, String arg1)
throws CertificateException {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
}
maven配置
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.1</version>
</dependency>
本文代码均可以从github下载,地址 https://github.com/niuhp/toolbox
欢迎来到这里!
我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。
注册 关于