`
收藏列表
标题 标签 来源
HttpClientWebService httpclent
package com.dic.bss.jike.filter.del;


/**
 * 日期 : 2012-3-2  上午10:00:39<br>
 * 作者 : zhangliuhua<br>
 * 项目 : httpClientWebService<br>
 * 功能 : <br>
 */
public class HttpClientWebService {
	
	public void main(String[] args){
		HttpClientParams httpClientParams = new HttpClientParams();
	    httpClientParams.setVersion( HttpVersion.HTTP_1_1 );
	    httpClientParams.makeLenient();
	    httpClientParams.setAuthenticationPreemptive( false );
	    httpClientParams.setVirtualHost( "" );//IP为调用地址服务器IP

	//创建httpclient

	   HttpClient httpClient = new HttpClient( httpClientParams, new MultiThreadedHttpConnectionManager());
	    httpClientParams.setSoTimeout( 10000 );
	    httpClient.setParams( httpClientParams );
	    httpClient.getHttpConnectionManager().getParams().setConnectionTimeout( (int) 10000 );

	   HostConfiguration hostConf = new HostConfiguration();

	  
	    hostConf.setHost( "192.168.10.158", 8002, "http" );
	    httpClient.setHostConfiguration( hostConf );

	   GetMethod method = new GetMethod();
	    method.setFollowRedirects( false );
	    method.setDoAuthentication( false );
	    method.getProxyAuthState().setAuthAttempted( false );
	    method.getProxyAuthState().setAuthRequested( false );
	    if( null != headers )
	     for( Header header : headers ) {
	      method.addRequestHeader( header.getName(), header.getValue() );
	     }
	   

	   method.getParams().setCookiePolicy( CookiePolicy.IGNORE_COOKIES );
	    String cookieStr = "";
	    if ( null != cookies ) {
	     for ( Cookie cookie : cookies ) {
	      cookieStr += cookie.getName() + "=" + cookie.getValue() + "; ";
	     }
	     if ( cookieStr.length() > 2 )
	      cookieStr = cookieStr.substring( 0, cookieStr.length() - 2 );
	     method.setRequestHeader( "Cookie", cookieStr );
	    }

	   method.setPath( !path.trim().startsWith( "/" ) ? "/" : "" + path.trim() );//调用地址
	    method.getParams().setParameter( HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler( 3, true ) );

	   Map<String,Object> returnMap = new HashMap<String,Object>();
	    String response = "";
	    try {
	     int statusCode = httpClient.executeMethod( method );//执行调用,返回int型 e.g:200,404 
	     returnMap.put( "statusCode", statusCode );
	     if ( statusCode != HttpStatus.SC_OK ) {//比较查看返回值
	     log.error( "Method Failed" + method.getStatusLine() );
	      throw new Exception( "Status Code is " + statusCode );
	     }
	     if( !method.getResponseCharSet().equalsIgnoreCase( "utf-8" ) )
	      response = IOUtils.toString( method.getResponseBodyAsStream(), "UTF-8" );
	     else
	      response = method.getResponseBodyAsString();
	     returnMap.put( "body", response );
	     returnMap.put( "header", method.getResponseHeaders() );
	}

}
HttpClientPoolableObjectFactory httpclent
package com.dic.bss.jike.filter.del;


import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.pool.BasePoolableObjectFactory;
import org.apache.http.HttpVersion;
import org.apache.http.client.params.ClientPNames;
import org.apache.http.client.params.CookiePolicy;
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.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;

public class HttpClientPoolableObjectFactory extends BasePoolableObjectFactory {

	private static final Log log = LogFactory.getLog(HttpClientPoolableObjectFactory.class);

	private static final ClientConnectionManager connMng;
	private static final IdleConnectionEvictor evictor;

	static {
		SchemeRegistry schemeRegistry = new SchemeRegistry();
		schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));

		connMng = new ThreadSafeClientConnManager(schemeRegistry);
		((ThreadSafeClientConnManager) connMng).setMaxTotal(10);//EsbConfig.getInt("HTTP_MAX_CONN")
		((ThreadSafeClientConnManager) connMng).setDefaultMaxPerRoute(2);//EsbConfig.getInt("HTTP_MAX_CONN_PRE_ROUTE")
		evictor = new IdleConnectionEvictor();
		evictor.start();
	}

	public static class IdleConnectionEvictor extends Thread {
		private static final int INTERVAL = 5000;// 毫秒

		public IdleConnectionEvictor() {
			super("HttpClient_IdleConnectionEvictor");
		}

		public void run() {
			while (!isInterrupted()) {
				try {
					sleep(INTERVAL);
					connMng.closeExpiredConnections();
					
					//TODO:connMng.closeIdleConnections(INTERVAL, TimeUnit.MILLISECONDS);

				} catch (InterruptedException e) {
					log.info("IdleConnectionEvictor任务结束!");
					break;
				} catch (Throwable ex) {
					log.error("定时关闭http连接出错!", ex);
				}
			}
		}
	}

	public Object makeObject() throws Exception {
		HttpParams params = new BasicHttpParams();
		HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
		HttpConnectionParams.setSoReuseaddr(params, true);
		HttpConnectionParams.setLinger(params, 0);
		params.setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.IGNORE_COOKIES);
		params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, new Integer(1000));//固定设置为1s

		return new DefaultHttpClient(connMng, params);
	}

	public static void shutdownTask() {
		evictor.interrupt();
		connMng.shutdown();
	}
}
HSNHttpHelper httpclent
package com.dic.bss.jike.filter.del;

import java.io.IOException;
import java.net.ConnectException;
import java.net.URI;
import java.net.URISyntaxException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.pool.ObjectPool;
import org.apache.commons.pool.impl.StackObjectPoolFactory;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.util.EntityUtils;

public class HSNHttpHelper {
	private static final Log log = LogFactory.getLog(HSNHttpHelper.class);

	private static ObjectPool httpClientPool = null;
	private static long httpClientPoolMaxCount = 0;
	static {
		httpClientPoolMaxCount = 10;// EsbConfig.getInt("HTTP_CLIENT_POOL_MAX_COUNT");
		// httpClientPool = new StackObjectPoolFactory(new
		// HttpClientPoolableObjectFactory(),
		// EsbConfig.getInt("HTTP_CLIENT_POOL_MAX_COUNT"),EsbConfig.getInt("HTTP_CLIENT_POOL_MIN_COUNT")).createPool();
		httpClientPool = new StackObjectPoolFactory(new HttpClientPoolableObjectFactory(), 10, 2).createPool();
	}

	// 以http的POST方式发送请求.假设返回数据均为文本。暂不考虑返回非文本数据。
	public static HttpRetBean doUrlPostStr(URI uri, Header[] headers, byte[] reqBody, int timeOut, boolean isReadResponse) throws ConnectException,
			IOException, URISyntaxException {
		return doUrlReqStr(new HttpPost(uri), headers, reqBody, timeOut, isReadResponse);
	}

	public static HttpRetBean doUrlPostStr(URI uri, String pathInfo, Header[] headers, byte[] reqBody, int timeOut, String ContentType, String reqCharset,
			String resCharset, boolean isReadResponse) throws ConnectException, IOException, URISyntaxException {
		return doUrlReqStr(new HttpPost(new URI(uri.getScheme(), uri.getAuthority(), uri.getHost(), uri.getPort(), uri.getPath() + pathInfo, uri.getQuery(),
				uri.getFragment())), headers, reqBody, timeOut, isReadResponse);
	}

	private static HttpRetBean doUrlReqStr(HttpUriRequest request, Header[] headers, byte[] reqBody, int timeOut, boolean isReadResponse)
			throws ConnectException, IOException, URISyntaxException {
		request.setHeaders(headers);
		request.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, new Integer(timeOut));
		if (reqBody != null && request instanceof HttpEntityEnclosingRequestBase) {
			ByteArrayEntity entity = new ByteArrayEntity(reqBody);
			entity.setChunked(false);
			((HttpEntityEnclosingRequestBase) request).setEntity(entity);
		}

		HttpClient httpClient = null;
		try {
			httpClient = (HttpClient) httpClientPool.borrowObject();

			HttpResponse res = httpClient.execute(request);
			byte[] retData = null;
			if (isReadResponse) {
				retData = EntityUtils.toByteArray(res.getEntity());// autoClose
			} else {
				res.getEntity().getContent().close();
			}
			return new HttpRetBean(res.getStatusLine().getStatusCode(), res.getAllHeaders(), retData);
		} catch (ConnectException e) {
			request.abort();
			throw e;
		} catch (IOException e) {
			request.abort();
			throw e;
		} catch (URISyntaxException e) {
			request.abort();
			throw e;
		} catch (Exception e) {
			try {
				throw new Exception(request.getURI().toString() + ":" + e.getMessage());
			} catch (Exception e2) {
			}

		} finally {
			if (httpClient != null) {
				try {
					httpClientPool.returnObject(httpClient);
				} catch (Exception e) {
					log.warn("HttpClient对象归还失败", e);
				}
			}
		}
		return null;
	}

	// 发送http请求.假设返回数据均为文本。暂不考虑返回非文本数据。
	public static HttpRetBean doUrlReqStr(URI uri, String httpMethod, String queryStr, Header[] headers, byte[] reqBody, int timeOut, boolean isReadResponse)
			throws ConnectException, IOException, URISyntaxException {

		if (httpMethod.equals(HttpPost.METHOD_NAME)) {
			return doUrlPostStr(new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(), uri.getPath(), queryStr, uri.getFragment()), headers,
					reqBody, timeOut, isReadResponse);
		} else if (httpMethod.equals(HttpGet.METHOD_NAME)) {
			return doUrlReqStr(new HttpGet(uri), headers, reqBody, timeOut, isReadResponse);
		} else if (httpMethod.equals(HttpDelete.METHOD_NAME)) {
			return doUrlReqStr(new HttpDelete(uri), headers, reqBody, timeOut, isReadResponse);
		} else if (httpMethod.equals(HttpPut.METHOD_NAME)) {
			return doUrlReqStr(new HttpPut(uri), headers, reqBody, timeOut, isReadResponse);
		} else {
			throw new IOException("http请求方法错误:" + httpMethod);
		}
	}

	public static HttpRetBean doUrlReqStr(URI uri, String httpMethod, String pathInfo, String queryStr, Header[] headers, byte[] reqBody, int timeOut,
			boolean isReadResponse) throws ConnectException, IOException, URISyntaxException {

		if (httpMethod.equals(HttpPost.METHOD_NAME)) {
			return doUrlPostStr(
					new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(), uri.getPath() + pathInfo, queryStr, uri.getFragment()), headers,
					reqBody, timeOut, isReadResponse);
		} else if (httpMethod.equals(HttpGet.METHOD_NAME)) {
			return doUrlReqStr(
					new HttpGet(
							new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(), uri.getPath() + pathInfo, queryStr, uri.getFragment())),
					headers, reqBody, timeOut, isReadResponse);
		} else if (httpMethod.equals(HttpDelete.METHOD_NAME)) {
			return doUrlReqStr(
					new HttpDelete(new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(), uri.getPath() + pathInfo, queryStr,
							uri.getFragment())), headers, reqBody, timeOut, isReadResponse);
		} else if (httpMethod.equals(HttpPut.METHOD_NAME)) {
			return doUrlReqStr(
					new HttpPut(
							new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(), uri.getPath() + pathInfo, queryStr, uri.getFragment())),
					headers, reqBody, timeOut, isReadResponse);
		} else {
			throw new IOException("http请求方法错误:" + httpMethod);
		}
	}

	// yangxiao 获取对象池numActive
	public static long getHttpClientPoolNumActive() {
		return httpClientPool.getNumActive();
	}

	// yangxiao 获取对象池NumIdle
	public static long getHttpClientPoolMaxNum() {
		return httpClientPoolMaxCount;
	}
}
Global site tag (gtag.js) - Google Analytics