package com.zhj.httpxml.client;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.zip.GZIPInputStream;
import java.util.zip.InflaterInputStream;
import javax.net.ssl.SSLHandshakeException;
import org.apache.commons.lang.StringUtils;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.ProtocolException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.HttpRequestRetryHandler;
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.URIUtils;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.DefaultRedirectStrategy;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
/**
* 类HttpClinetServiceImpl.java的实现描述:httpclinet
*
* @author zhj
*/
public class HttpClientService {
/**
* user_agent
*/
private static final String USER_AGENT = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.79 Safari/535.11";
/**
* 最大连接数
*/
private int maxConnections = 5000;
/**
* 链接超时时间
*/
private int connectionTimeout = 1000;
/**
* 每个主机最大连接数
*/
private int maxPerRoute = 100;
/**
* 读取超时时间
*/
private int readTimeout = 1000;
/**
* 请求失败后重试次数
*/
private int retry = 1;
/**
* httpClient
*/
private HttpClient httpClient;
/** init 只是调用afterPropertiesSet,在没有通过spring注入时使用 */
public HttpClientService init() throws Exception {
if (this.httpClient == null) {
this.afterPropertiesSet();
}
return this;
}
public void afterPropertiesSet() throws Exception {
ThreadSafeClientConnManager manager = new ThreadSafeClientConnManager();
manager.setMaxTotal(maxConnections);
manager.setDefaultMaxPerRoute(maxPerRoute);
HttpParams params = new BasicHttpParams();
params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectionTimeout);
params.setParameter(CoreConnectionPNames.SO_TIMEOUT, readTimeout);
DefaultHttpClient httpClient = new DefaultHttpClient(manager, params);
httpClient.setRedirectStrategy(new DefaultRedirectStrategy() {
@Override
protected URI createLocationURI(String location) throws ProtocolException {
try {
int index = location.indexOf("?");
if (index != -1) {
String url = location.substring(0, index + 1);
String params = location.substring(index + 1);
StringBuilder sb = new StringBuilder(url);
String[] pairs = params.split("&");
if (pairs != null && pairs.length > 0) {
for (String pair : pairs) {
String[] param = pair.split("=", 2);
if (param != null && param.length == 2) {
sb.append(param[0]).append("=").append(URLEncoder.encode(param[1], "utf-8")).append("&");
}
}
location = sb.toString();
} else if (params.length() > 0) {
String[] param = params.split("=", 2);
sb.append(param[0]).append("=").append(URLEncoder.encode(param[1], "utf-8"));
location = sb.toString();
}
}
} catch (UnsupportedEncodingException e) {
}
return super.createLocationURI(location);
}
});
httpClient.setHttpRequestRetryHandler(new HttpRequestRetryHandler() {
@Override
public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
if (executionCount <= retry && !(exception instanceof SSLHandshakeException)) {
return true;
}
return false;
}
});
this.httpClient = httpClient;
}
/**
* 通过HTTP请求调用,获得HTTP响应内容
*
* @param requestUrl 请求URL
* @param isPost 是否是post方式提交
* @param params 参数
* @return
* @throws IOException
* @throws URISyntaxException
* @throws ClientProtocolException
*/
public String getHttpResponseContent(String requestUrl, Map<String, Object> params, boolean isPost)
throws URISyntaxException,
ClientProtocolException,
IOException {
HttpRequest request = getRequest(requestUrl, params, isPost);
return request.getResponseAsString();
}
/**
* 通过HTTP请求调用,获得HTTP响应内容 -(Stream)调用处要关闭流
*
* @param requestUrl 请求URL
* @param params 参数
* @param isPost 是否是post方式提交
* @param allowCompression 是否允许压缩
* @return
* @throws IOException
* @throws URISyntaxException
* @throws ClientProtocolException
*/
public InputStream getHttpResponseStream(String requestUrl, Map<String, Object> params, boolean isPost,
boolean allowCompression) throws URISyntaxException,
ClientProtocolException, IOException {
HttpRequest request = getRequest(requestUrl, params, isPost);
InputStream result = request.getResponseAsStream(allowCompression);
// 在调用处要关闭流
// request.release();
return result;
}
/** Query参数的value为string */
public InputStream strHttpResponseStream(String requestUrl, Map<String, String> params, boolean isPost,
boolean allowCompression) throws URISyntaxException,
ClientProtocolException, IOException {
Map<String, Object> map = new HashMap<String, Object>(params);
- 1
- 2
前往页