HttpClient+ Spring實現多線程

HttpClient通過MultiThreadedHttpConnectionManager實現多線程通訊

HttpConnectionManagerParams設置connectionTimeout鏈接超時,soTimeout讀取數據超時,maxTotalConnections,defaultMaxConnectionsPerHost等等參數

MultiThreadedHttpConnectionManager多線程中屬性params是HttpConnectionManagerParams

Spring中xml配置文件如下

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="
    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">

	<!-- httpclient線程池 -->
	<bean id="connectionManagerParams" class="org.apache.commons.httpclient.params.HttpConnectionManagerParams">
		<property name="connectionTimeout" value="10000"/>
		<property name="soTimeout" value="10000"/>
		<property name="maxTotalConnections" value="30"/>
		<property name="defaultMaxConnectionsPerHost" value="20"/>
	</bean> 
	
	<bean id="connectionManager" class="org.apache.commons.httpclient.MultiThreadedHttpConnectionManager">
		<property name="params" ref="connectionManagerParams"/>
	</bean>
	
	<bean id="httpclient" class="org.apache.commons.httpclient.HttpClient">
		<constructor-arg>
			<ref bean="connectionManager"/>
		</constructor-arg>
	</bean>
	
	<bean id="httpClientUtil" class="com.chinaums.utils.HttpClientUtil">
		<property name="httpclient" ref="httpclient"/>
	</bean>
	
	
</beans>
 

通用文件httpClientUtil

 

 

package com.chinaums.utils;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;


/**
 * httpClient工具類
 * 

 * 
 */
public class HttpClientUtil {

	private  HttpClient httpclient;

	public void setHttpclient(HttpClient httpclient) {
		this.httpclient = httpclient;
	}

	public HttpClientUtil() {

	}

	/**
	 * 以get方式發送http請求
	 * 
	 * @param url
	 * @return
	 */
	public String sendRequest(String url) {
		GetMethod getMethod = new GetMethod(url);
		try {
			getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,new DefaultHttpMethodRetryHandler());
//			httpclient.getHttpConnectionManager().getParams().setConnectionTimeout(6000);
//			getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT,6000);
			httpclient.executeMethod(getMethod);
			return getMethod.getResponseBodyAsString();
		} catch (Exception e) {
			e.printStackTrace();
			return "FAIL";
		}
		finally{
			getMethod.releaseConnection();
		}
	}
	
	/**
	 * 以get方式發送http請求
	 * 
	 * @param url
	 * @return
	 */
	public boolean isActive(String url) {
		boolean flag = false;
		GetMethod getMethod = new GetMethod(url);
		try {
			getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,new DefaultHttpMethodRetryHandler());
			int statusCode = httpclient.executeMethod(getMethod);
			if(statusCode==200){
				flag = true;
			}
			return flag;
		} catch (Exception e) {
			e.printStackTrace();
			return flag;
		}
		finally{
			getMethod.releaseConnection();
		}
	}
	
	/**
	 * 以post方式發送http請求
	 * 
	 * @param url
	 * @return
	 */
	public  int sendRequestAsPost(String url) {
		PostMethod postMethod = new PostMethod(url);
		try {
			postMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,new DefaultHttpMethodRetryHandler());
			httpclient.getHttpConnectionManager().getParams().setConnectionTimeout(1000);
			postMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT,1000);

			int statusCode = httpclient.executeMethod(postMethod);
			return statusCode;
		} catch (Exception e) {
			e.printStackTrace();
			return 500;
		}
		finally{
			postMethod.releaseConnection();
		}
	}

	/**
	 * 驗證請求是否是本機發出
	 * 
	 * @param request
	 *            true本機發出 false非本機發出
	 * @return
	 */
	public static boolean isRequestFromSelf(HttpServletRequest request) {
		if (getRemoteIpAddr(request).equals(getLocalIpAddr()))
			return true;
		else
			return false;
	}

	/**
	 * 獲取遠程客戶端IP地址
	 * 
	 * @param request
	 * @return
	 */
	public static String getRemoteIpAddr(HttpServletRequest request) {
		String ip = request.getHeader("X-Forwarded-For");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
			ip = request.getHeader("Proxy-Client-IP");

		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
			ip = request.getHeader("WL-Proxy-Client-IP");

		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
			ip = request.getHeader("HTTP_CLIENT_IP");

		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
			ip = request.getHeader("HTTP_X_FORWARDED_FOR");

		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
			ip = request.getRemoteAddr();

		if ("0:0:0:0:0:0:0:1".equals(ip.trim()))
			ip = "server";

		// 判斷請求是否是本機發出,如果是本機發出,那麼就獲取本機地址
		if ("127.0.0.1".equals(ip) || ip.equalsIgnoreCase("localhost"))
			ip = getLocalIpAddr();

		return ip;
	}

	/**
	 * 獲取本機IP地址
	 * 
	 * @return
	 */
	public static String getLocalIpAddr() {
		try {
			Enumeration netInterfaces = NetworkInterface.getNetworkInterfaces();
			InetAddress ip = null;
			String ipAddr = null;
			while (netInterfaces.hasMoreElements()) {
				NetworkInterface ni = (NetworkInterface) netInterfaces.nextElement();
				ip = (InetAddress) ni.getInetAddresses().nextElement();
				if (!ip.isSiteLocalAddress() && !ip.isLoopbackAddress() && ip.getHostAddress().indexOf(":") == -1) {
					ipAddr = ip.getHostAddress();
					break;
				}
			}
			return ipAddr;
		} catch (SocketException e) {
			e.printStackTrace();
			return null;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 判斷某回調地址是否是指定的網關地址
	 * 
	 * @param notifyUrl
	 * @param getwayList
	 * @return true 是網關 false不是網關地址
	 */
	public static boolean isLocalNotifyUrl(String notifyUrl, List getwayList) {
		boolean flag = false;
		for (Object object : getwayList) {
			String getway = (String) object;
			if (notifyUrl.toLowerCase().contains(getway)) {
				flag = true;
				break;
			}
		}
		return flag;
	}
	
	public static void main(String[] arg){
		HttpClient httpclient = new HttpClient();
		String url = "http://www.163.com";
		GetMethod method = new GetMethod(url);
		try {
			method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,new DefaultHttpMethodRetryHandler());
			int statusCode = httpclient.executeMethod(method);
			System.out.println(statusCode);
			byte[] responseBody = method.getResponseBody();
			System.out.println(new String(responseBody));
		} catch (Exception e) {
			e.printStackTrace();
		}
		finally{
			method.releaseConnection();
		}
	
		
	}
}
發佈了55 篇原創文章 · 獲贊 17 · 訪問量 16萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章