HttpClient+ Spring实现多线程

编程技术  /  houtizong 发布于 3年前   76

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;elsereturn 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();}}}

请勿发布不友善或者负能量的内容。与人为善,比聪明更重要!

留言需要登陆哦

技术博客集 - 网站简介:
前后端技术:
后端基于Hyperf2.1框架开发,前端使用Bootstrap可视化布局系统生成

网站主要作用:
1.编程技术分享及讨论交流,内置聊天系统;
2.测试交流框架问题,比如:Hyperf、Laravel、TP、beego;
3.本站数据是基于大数据采集等爬虫技术为基础助力分享知识,如有侵权请发邮件到站长邮箱,站长会尽快处理;
4.站长邮箱:[email protected];

      订阅博客周刊 去订阅

文章归档

文章标签

友情链接

Auther ·HouTiZong
侯体宗的博客
© 2020 zongscan.com
版权所有ICP证 : 粤ICP备20027696号
PHP交流群 也可以扫右边的二维码
侯体宗的博客