HttpClientManager.java 2.89 KB
package com.diligrp.website.util.http;


import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

/**
 * 
 * <B>httpClient管理器</B>
 * <B>Copyright</B> Copyright (c) 2014 www.diligrp.com All rights reserved. <br />
 * 本软件源代码版权归地利集团,未经许可不得任意复制与传播.<br />
 * <B>Company</B> 地利集团
 * @createTime 2014年5月12日 下午4:45:38
 * @author mengxf
 */
public class HttpClientManager {
	private int timeout;
	/** The http params. */
	private static HttpParams httpParams;
	/** The connection manager. */
	private static ClientConnectionManager connectionManager;

	public void init() {
		httpParams = new BasicHttpParams();
		HttpConnectionParams.setConnectionTimeout(httpParams, timeout);
		HttpConnectionParams.setSoTimeout(httpParams, timeout);
		SchemeRegistry registry = new SchemeRegistry();
		registry.register(new Scheme("http", 80, PlainSocketFactory
				.getSocketFactory()));
		registry.register(new Scheme("https", 443, SSLSocketFactory
				.getSocketFactory()));

		connectionManager = new ThreadSafeClientConnManager(registry);
	}

	public static DefaultHttpClient getHttpClient() {
		DefaultHttpClient httpClient = new DefaultHttpClient(connectionManager,
				httpParams);
		DefaultHttpRequestRetryHandler handler = new DefaultHttpRequestRetryHandler(3,false);
		httpClient.setHttpRequestRetryHandler(handler); 
//		HttpRequestRetryHandler handler = new HttpRequestRetryHandler() {
//
//			public boolean retryRequest(IOException exception,
//					int executionCount, HttpContext context) {
//				if (executionCount >= 2) {
//					// Do not retry if over max retry count
//					return false;
//				}
//				if (exception instanceof NoHttpResponseException) {
//					// Retry if the server dropped connection on us
//					return true;
//				}
//				if (exception instanceof SSLHandshakeException) {
//					// Do not retry on SSL handshake exception
//					return false;
//				}
//				HttpRequest request = (HttpRequest) context
//						.getAttribute(ExecutionContext.HTTP_REQUEST);
//				boolean idempotent = !(request instanceof HttpEntityEnclosingRequest);
//				if (idempotent) {
//					// Retry if the request is considered idempotent
//					return true;
//				}
//				return false;
//			}
//		};
		//去掉重试
		//httpClient.setHttpRequestRetryHandler(handler);
		return httpClient;
	}

	public void setTimeout(int timeout) {
		this.timeout = timeout;
	}
}