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>  

 

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();   
        }   
       
           
    }   
}  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值