/*
/**
* 网络请求工具类
* @author 阿福
*
*/
public class HttpUtils {
public final static HttpCache sHttpCache = new HttpCache();
private final DefaultHttpClient httpClient;
private final HttpContext httpContext = new BasicHttpContext();
private HttpRedirectHandler httpRedirectHandler;
/**
* 构造方法,默认联网15秒超时
*/
public HttpUtils() {
this(HttpUtils.DEFAULT_CONN_TIMEOUT, null);
}
/**
* 构造方法设置超时时间
* @param connTimeout 超时时间毫秒
*/
public HttpUtils(int connTimeout) {
this(connTimeout, null);
}
/**
* 构造方法,浏览器的信息包
* @param userAgent
*/
public HttpUtils(String userAgent) {
this(HttpUtils.DEFAULT_CONN_TIMEOUT, userAgent);
}
/**
* 构造方法
* @param connTimeout 链接超时时间,毫秒单位
* @param userAgent 浏览器的信息包
*/
public HttpUtils(int connTimeout, String userAgent) {
HttpParams params = new BasicHttpParams();
ConnManagerParams.setTimeout(params, connTimeout);
HttpConnectionParams.setSoTimeout(params, connTimeout);
HttpConnectionParams.setConnectionTimeout(params, connTimeout);
if (TextUtils.isEmpty(userAgent)) {
userAgent = OtherUtils.getUserAgent(null);
}
HttpProtocolParams.setUserAgent(params, userAgent);
ConnManagerParams.setMaxConnectionsPerRoute(params, new ConnPerRouteBean(10));
ConnManagerParams.setMaxTotalConnections(params, 10);
HttpConnectionParams.setTcpNoDelay(params, true);
HttpConnectionParams.setSocketBufferSize(params, 1024 * 8);
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
schemeRegistry.register(new Scheme("https", DefaultSSLSocketFactory.getSocketFactory(), 443));
httpClient = new DefaultHttpClient(new ThreadSafeClientConnManager(params, schemeRegistry), params);
httpClient.setHttpRequestRetryHandler(new RetryHandler(DEFAULT_RETRY_TIMES));
httpClient.addRequestInterceptor(new HttpRequestInterceptor() {
@Override
public void process(org.apache.http.HttpRequest httpRequest, HttpContext httpContext) throws org.apache.http.HttpException, IOException {
if (!httpRequest.containsHeader(HEADER_ACCEPT_ENCODING)) {
httpRequest.addHeader(HEADER_ACCEPT_ENCODING, ENCODING_GZIP);
}
}
});
httpClient.addResponseInterceptor(new HttpResponseInterceptor() {
@Override
public void process(HttpResponse response, HttpContext httpContext) throws org.apache.http.HttpException, IOException {
final HttpEntity entity = response.getEntity();
if (entity == null) {
return;
}
final Header encoding = entity.getContentEncoding();
if (encoding != null) {
for (HeaderElement element : encoding.getElements()) {
if (element.getName().equalsIgnoreCase("gzip")) {
response.setEntity(new GZipDecompressingEntity(response.getEntity()));
return;
}
}
}
}
});
}
// ************************************ default settings & fields ****************************
private String responseTextCharset = HTTP.UTF_8;
private long currentRequestExpiry = HttpCache.getDefaultExpiryTime();
private final static int DEFAULT_CONN_TIMEOUT = 1000 * 15; // 15s
private final static int DEFAULT_RETRY_TIMES = 3;
private static final String HEADER_ACCEPT_ENCODING = "Accept-Encoding";
private static final String ENCODING_GZIP = "gzip";
private final static int DEFAULT_POOL_SIZE = 3;
private final static PriorityExecutor EXECUTOR = new PriorityExecutor(DEFAULT_POOL_SIZE);
public HttpClient getHttpClient() {
return this.httpClient;
}
// ***************************************** config *******************************************
/**
* 配置请求文本编码,默认UTF-8
* @param charSet
* @return
*/
public HttpUtils configResponseTextCharset(String charSet) {
if (!TextUtils.isEmpty(charSet)) {
this.responseTextCharset = charSet;
}
return this;
}
/**
* http重定向处理
* @param httpRedirectHandler
* @return
*/
public HttpUtils configHttpRedirectHandler(HttpRedirectHandler httpRedirectHandler) {
this.httpRedirectHandler = httpRedirectHandler;
return this;
}
/**
* 配置http缓存大小
* @param httpCacheSize
* @return
*/
public HttpUtils configHttpCacheSize(int httpCacheSize) {
sHttpCache.setCacheSize(httpCacheSize);
return this;
}
/**
* 配置默认http缓存失效 ,默认是60秒
* @param defaultExpiry
* @return
*/
public HttpUtils configDefaultHttpCacheExpiry(long defaultExpiry) {
HttpCache.setDefaultExpiryTime(defaultExpiry);
currentRequestExpiry = HttpCache.getDefaultExpiryTime();
return this;
}
/**
* 配置当前http缓存失效,时间默认60秒
* @param currRequestExpiry
* @return
*/
public HttpUtils configCurrentHttpCacheExpiry(long currRequestExpiry) {
this.currentRequestExpiry = currRequestExpiry;
return this;
}
/**
* cookie存储配置
* @param cookieStore
* @return
*/
public HttpUtils configCookieStore(CookieStore cookieStore) {
httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
return this;
}
/**
* 配置浏览器信息包
* @param userAgent
* @return
*/
public HttpUtils configUserAgent(String userAgent) {
HttpProtocolParams.setUserAgent(this.httpClient.getParams(), userAgent);
return this;
}
/**
* 配置时间链接超时
* @param timeout
* @return
*/
public HttpUtils configTimeout(int timeout) {
final HttpParams httpParams = this.httpClient.getParams();
ConnManagerParams.setTimeout(httpParams, timeout);
HttpConnectionParams.setConnectionTimeout(httpParams, timeout);
return this;
}
/**
* 配置socket时间连接溢出
* @param timeout
* @return
*/
public HttpUtils configSoTimeout(int timeout) {
final HttpParams httpParams = this.httpClient.getParams();
HttpConnectionParams.setSoTimeout(httpParams, timeout);
return this;
}
/**
* 配置注册Scheme
* @param scheme
* @return
*/
public HttpUtils configRegisterScheme(Scheme scheme) {
this.httpClient.getConnectionManager().getSchemeRegistry().register(scheme);
return this;
}
/**
* 配置SSLSocketFactory
* @param sslSocketFactory
* @return
*/
public HttpUtils configSSLSocketFactory(SSLSocketFactory sslSocketFactory) {
Scheme scheme = new Scheme("https", sslSocketFactory, 443);
this.httpClient.getConnectionManager().getSchemeRegistry().register(scheme);
return this;
}
/**
* 配置请求重试次数
* @param count 重试次数
* @return
*/
public HttpUtils configRequestRetryCount(int count) {
this.httpClient.setHttpRequestRetryHandler(new RetryHandler(count));
return this;
}
/**
* 配置请求线程池个数
* @param threadPoolSize 线程池个数
* @return
*/
public HttpUtils configRequestThreadPoolSize(int threadPoolSize) {
HttpUtils.EXECUTOR.setPoolSize(threadPoolSize);
return this;
}
// ***************************************** send request 发送请求*******************************************
/**
* 发送异步网络请求 -重要
* @param method get或者post请求等等
* @param url 网络请求路径
* @param callBack 回调
* @return
*/
public <T> HttpHandler<T> send(HttpRequest.HttpMethod method, String url,
RequestCallBack<T> callBack) {
return send(method, url, null, callBack);
}
/**
* 发送异步网络请求 -重要
* @param method get或者post请求等等
* @param url 网络请求路径
* @param params 请求参数
* @param callBack 回调
* @return
*/
public <T> HttpHandler<T> send(HttpRequest.HttpMethod method, String url, RequestParams params,
RequestCallBack<T> callBack) {
if (url == null) throw new IllegalArgumentException("url may not be null");
HttpRequest request = new HttpRequest(method, url);
return sendRequest(request, params, callBack);
}
/**
* 发送同步网络请求 -用得不多
* @param method get或者post等方法
* @param url 联网网络url
* @return
* @throws HttpException
*/
public ResponseStream sendSync(HttpRequest.HttpMethod method, String url) throws HttpException {
return sendSync(method, url, null);
}
/**
* 发送同步网络请求 -用得不多
* @param method get或者post等方法
* @param url 联网网络url
* @param params 请求参数
* @return
* @throws HttpException
*/
public ResponseStream sendSync(HttpRequest.HttpMethod method, String url, RequestParams params) throws HttpException {
if (url == null) throw new IllegalArgumentException("url may not be null");
HttpRequest request = new HttpRequest(method, url);
return sendSyncRequest(request, params);
}
// ***************************************** download 下载*******************************************
/**
* 下载文件方法
* @param url 下载文件的url
* @param target 下载保存的目录
* @param callback 回调
* @return
*/
public HttpHandler<File> download(String url, String target,
RequestCallBack<File> callback) {
return download(HttpRequest.HttpMethod.GET, url, target, null, false, false, callback);
}
/**
* 下载文件方法
* @param url 下载文件的url
* @param target 下载保存的目录
* @param autoResume 是否自动恢复下载
* @param callback 回调
* @return
*/
public HttpHandler<File> download(String url, String target,
boolean autoResume, RequestCallBack<File> callback) {
return download(HttpRequest.HttpMethod.GET, url, target, null, autoResume, false, callback);
}
/**
* 下载文件方法
* @param url 下载文件的url
* @param target 下载保存的目录
* @param autoResume 是否自动恢复下载
* @param autoRename 是否自动重命名
* @param callback 回调
* @return
*/
public HttpHandler<File> download(String url, String target,
boolean autoResume, boolean autoRename, RequestCallBack<File> callback) {
return download(HttpRequest.HttpMethod.GET, url, target, null, autoResume, autoRename, callback);
}
/**
* 下载文件方法
* @param url 下载文件的url
* @param target 下载保存的目录
* @param params 参数类
* @param callback 回调
* @return
*/
public HttpHandler<File> download(String url, String target,
RequestParams params, RequestCallBack<File> callback) {
return download(HttpRequest.HttpMethod.GET, url, target, params, false, false, callback);
}
/**
* 下载文件方法
* @param url 下载文件的url
* @param target 下载保存的目录
* @param params 参数类
* @param autoResume 是否自动恢复下载
* @param callback 回调
* @return
*/
public HttpHandler<File> download(String url, String target,
RequestParams params, boolean autoResume, RequestCallBack<File> callback) {
return download(HttpRequest.HttpMethod.GET, url, target, params, autoResume, false, callback);
}
/**
* 下载文件方法
* @param url 下载文件的url
* @param target 下载保存的目录
* @param params 参数
* @param autoResume 是否自动恢复
* @param autoRename 是否自动命名
* @param callback 回调
* @return
*/
public HttpHandler<File> download(String url, String target,
RequestParams params, boolean autoResume, boolean autoRename, RequestCallBack<File> callback) {
return download(HttpRequest.HttpMethod.GET, url, target, params, autoResume, autoRename, callback);
}
/**
* 下载文件方法
* @param method 请求用get还是post等
* @param url 下载文件的url
* @param target 下载保存的目录
* @param params 参数
* @param callback 回调
* @return
*/
public HttpHandler<File> download(HttpRequest.HttpMethod method, String url, String target,
RequestParams params, RequestCallBack<File> callback) {
return download(method, url, target, params, false, false, callback);
}
/**
* 下载文件方法
* @param method 请求用get还是post等
* @param url 下载文件的url
* @param target 下载保存的目录
* @param params 参数
* @param autoResume 是否自动恢复下载
* @param callback 回调
* @return
*/
public HttpHandler<File> download(HttpRequest.HttpMethod method, String url, String target,
RequestParams params, boolean autoResume, RequestCallBack<File> callback) {
return download(method, url, target, params, autoResume, false, callback);
}
/**
* 下载文件方法
* @param method 请求用get还是post等
* @param url 下载文件的url
* @param target 下载保存的目录
* @param params 参数
* @param autoResume 是否自动恢复下载
* @param autoRename 是否自动重命名
* @param callback 回调
* @return
*/
public HttpHandler<File> download(HttpRequest.HttpMethod method, String url, String target,
RequestParams params, boolean autoResume, boolean autoRename, RequestCallBack<File> callback) {
if (url == null) throw new IllegalArgumentException("url may not be null");
if (target == null) throw new IllegalArgumentException("target may not be null");
HttpRequest request = new HttpRequest(method, url);
HttpHandler<File> handler = new HttpHandler<File>(httpClient, httpContext, responseTextCharset, callback);
handler.setExpiry(currentRequestExpiry);
handler.setHttpRedirectHandler(httpRedirectHandler);
if (params != null) {
request.setRequestParams(params, handler);
handler.setPriority(params.getPriority());
}
handler.executeOnExecutor(EXECUTOR, request, target, autoResume, autoRename);
return handler;
}
private <T> HttpHandler<T> sendRequest(HttpRequest request, RequestParams params, RequestCallBack<T> callBack) {
HttpHandler<T> handler = new HttpHandler<T>(httpClient, httpContext, responseTextCharset, callBack);
handler.setExpiry(currentRequestExpiry);
handler.setHttpRedirectHandler(httpRedirectHandler);
request.setRequestParams(params, handler);
if (params != null) {
handler.setPriority(params.getPriority());
}
handler.executeOnExecutor(EXECUTOR, request);
return handler;
}
private ResponseStream sendSyncRequest(HttpRequest request, RequestParams params) throws HttpException {
SyncHttpHandler handler = new SyncHttpHandler(httpClient, httpContext, responseTextCharset);
handler.setExpiry(currentRequestExpiry);
handler.setHttpRedirectHandler(httpRedirectHandler);
request.setRequestParams(params);
return handler.sendRequest(request);
}
}
xUtils 中的HttpUtils全面注释
最新推荐文章于 2024-08-15 18:37:29 发布