spring MVC 管理HttpClient---实现在java中直接向Controller发送请求

spring MVC中,大多数时候是由客户端的页面通过ajax等方式向controller发送请求,但有时候需要在Java代码中直接向controller发送请求,这时可以使用HttpCilent实现。

首先用到的包是httpclient-4.3.5.jar和httpcore-4.3.2.jar 

先看下面代码:

[java]  view plain  copy
  1. package module.system.common;  
  2.   
  3. import java.io.IOException;  
  4. import java.util.ArrayList;  
  5. import java.util.HashMap;  
  6. import java.util.List;  
  7. import java.util.Map;  
  8. import java.util.Set;  
  9.   
  10. import org.apache.http.NameValuePair;  
  11. import org.apache.http.client.ClientProtocolException;  
  12. import org.apache.http.client.entity.UrlEncodedFormEntity;  
  13. import org.apache.http.client.methods.CloseableHttpResponse;  
  14. import org.apache.http.client.methods.HttpGet;  
  15. import org.apache.http.client.methods.HttpPost;  
  16. import org.apache.http.impl.client.CloseableHttpClient;  
  17. import org.apache.http.impl.client.HttpClients;  
  18. import org.apache.http.message.BasicNameValuePair;  
  19. import org.apache.http.util.EntityUtils;  
  20.   
  21.   
  22.   
  23. /** 
  24.  * 在java中处理http请求. 
  25.  * @author nagsh 
  26.  * 
  27.  */  
  28. public class HttpDeal {  
  29.     /** 
  30.      * 处理get请求. 
  31.      * @param url  请求路径 
  32.      * @return  json 
  33.      */  
  34.     public String get(String url){  
  35.         //实例化httpclient  
  36.         CloseableHttpClient httpclient = HttpClients.createDefault();  
  37.         //实例化get方法  
  38.         HttpGet httpget = new HttpGet(url);   
  39.         //请求结果  
  40.         CloseableHttpResponse response = null;  
  41.         String content ="";  
  42.         try {  
  43.             //执行get方法  
  44.             response = httpclient.execute(httpget);  
  45.             if(response.getStatusLine().getStatusCode()==200){  
  46.                 content = EntityUtils.toString(response.getEntity(),"utf-8");  
  47.                 System.out.println(content);  
  48.             }  
  49.         } catch (ClientProtocolException e) {  
  50.             e.printStackTrace();  
  51.         } catch (IOException e) {  
  52.             e.printStackTrace();  
  53.         }  
  54.         return content;  
  55.     }  
  56.     /** 
  57.      * 处理post请求. 
  58.      * @param url  请求路径 
  59.      * @param params  参数 
  60.      * @return  json 
  61.      */  
  62.     public String post(String url,Map<String, String> params){  
  63.         //实例化httpClient  
  64.         CloseableHttpClient httpclient = HttpClients.createDefault();  
  65.         //实例化post方法  
  66.         HttpPost httpPost = new HttpPost(url);   
  67.         //处理参数  
  68.         List<NameValuePair> nvps = new ArrayList <NameValuePair>();    
  69.         Set<String> keySet = params.keySet();    
  70.         for(String key : keySet) {    
  71.             nvps.add(new BasicNameValuePair(key, params.get(key)));    
  72.         }    
  73.         //结果  
  74.         CloseableHttpResponse response = null;  
  75.         String content="";  
  76.         try {  
  77.             //提交的参数  
  78.             UrlEncodedFormEntity uefEntity  = new UrlEncodedFormEntity(nvps, "UTF-8");  
  79.             //将参数给post方法  
  80.             httpPost.setEntity(uefEntity);  
  81.             //执行post方法  
  82.             response = httpclient.execute(httpPost);  
  83.             if(response.getStatusLine().getStatusCode()==200){  
  84.                 content = EntityUtils.toString(response.getEntity(),"utf-8");  
  85.                 System.out.println(content);  
  86.             }  
  87.         } catch (ClientProtocolException e) {  
  88.             e.printStackTrace();  
  89.         } catch (IOException e) {  
  90.             e.printStackTrace();  
  91.         }   
  92.         return content;  
  93.     }  
  94.     public static void main(String[] args) {  
  95.         HttpDeal hd = new HttpDeal();  
  96.         hd.get("http://localhost:8080/springMVC/userType/getAll.do");  
  97.         Map<String,String> map = new HashMap();  
  98.         map.put("id","1");  
  99.         hd.post("http://localhost:8080/springMVC/menu/getChildren.do",map);  
  100.     }  
  101.   
  102. }  
这个类里的get和post方法分别可以实现get请求和post请求,如果单单在一个java测试类里边运行是没问题的,但在controller或jsp中调用,会抛异常。为什么呢?由于是在springMVC中,所以,我们应该把它交给spring来管理。

首先是:httpClient-servlet.xml

[html]  view plain  copy
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:context="http://www.springframework.org/schema/context"  
  4.     xmlns:p="http://www.springframework.org/schema/p"   
  5.     xmlns:aop="http://www.springframework.org/schema/aop"  
  6.     xmlns:tx="http://www.springframework.org/schema/tx"  
  7.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  8.     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd  
  9.     http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd  
  10.     http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd  
  11.     http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">  
  12.     <!-- 配置占位符 -->  
  13.     <bean  
  14.         class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  
  15.         <property name="location" value="classpath:/httpclient.properties" />  
  16.     </bean>  
  17.     <!-- 定义httpclient连接池 -->  
  18.     <bean id="httpClientConnectionManager" class="org.apache.http.impl.conn.PoolingHttpClientConnectionManager" destroy-method="close">  
  19.         <!-- 设置连接总数 -->  
  20.         <property name="maxTotal" value="${http.pool.maxTotal}"></property>  
  21.         <!-- 设置每个地址的并发数 -->  
  22.         <property name="defaultMaxPerRoute" value="${http.pool.defaultMaxPerRoute}"></property>  
  23.     </bean>  
  24.       
  25.     <!-- 定义 HttpClient工厂,这里使用HttpClientBuilder构建-->  
  26.     <bean id="httpClientBuilder" class="org.apache.http.impl.client.HttpClientBuilder" factory-method="create">  
  27.         <property name="connectionManager" ref="httpClientConnectionManager"></property>  
  28.     </bean>  
  29.       
  30.     <!-- 得到httpClient的实例 -->  
  31.     <bean id="httpClient" factory-bean="httpClientBuilder" factory-method="build"/>  
  32.       
  33.     <!-- 定期清理无效的连接 -->  
  34.     <bean class="module.system.common.IdleConnectionEvictor" destroy-method="shutdown">  
  35.         <constructor-arg index="0" ref="httpClientConnectionManager" />  
  36.         <!-- 间隔一分钟清理一次 -->  
  37.         <constructor-arg index="1" value="60000" />  
  38.     </bean>  
  39.       
  40.     <!-- 定义requestConfig的工厂 -->  
  41.     <bean id="requestConfigBuilder" class="org.apache.http.client.config.RequestConfig.Builder">  
  42.         <!-- 从连接池中获取到连接的最长时间 -->  
  43.         <property name="connectionRequestTimeout" value="${http.request.connectionRequestTimeout}"/>  
  44.         <!-- 创建连接的最长时间 -->  
  45.         <property name="connectTimeout" value="${http.request.connectTimeout}"/>  
  46.         <!-- 数据传输的最长时间 -->  
  47.         <property name="socketTimeout" value="${http.request.socketTimeout}"/>  
  48.         <!-- 提交请求前测试连接是否可用 -->  
  49.         <property name="staleConnectionCheckEnabled" value="${http.request.staleConnectionCheckEnabled}"/>  
  50.     </bean>     
  51.       
  52.     <!-- 得到requestConfig实例 -->  
  53.     <bean id="requestConfig" factory-bean="requestConfigBuilder" factory-method="build" />  
  54.       
  55.   
  56. </beans>  

httpclient.properties:

[plain]  view plain  copy
  1. #从连接池中获取到连接的最长时间  
  2. http.request.connectionRequestTimeout=500  
  3. #5000  
  4. http.request.connectTimeout=5000  
  5. #数据传输的最长时间  
  6. http.request.socketTimeout=30000  
  7. #提交请求前测试连接是否可用  
  8. http.request.staleConnectionCheckEnabled=true  
  9.   
  10. #设置连接总数  
  11. http.pool.maxTotal=200  
  12. #设置每个地址的并发数  
  13. http.pool.defaultMaxPerRoute=100  


一个必须的类,几记得修改xml里的该类的路径:

[java]  view plain  copy
  1. package module.system.common;  
  2.   
  3. import org.apache.http.conn.HttpClientConnectionManager;  
  4.   
  5. /** 
  6.  * 定期清理无效的http连接 
  7.  */  
  8. public class IdleConnectionEvictor extends Thread {  
  9.   
  10.     private final HttpClientConnectionManager connMgr;  
  11.       
  12.     private Integer waitTime;  
  13.   
  14.     private volatile boolean shutdown;  
  15.   
  16.     public IdleConnectionEvictor(HttpClientConnectionManager connMgr,Integer waitTime) {  
  17.         this.connMgr = connMgr;  
  18.         this.waitTime = waitTime;  
  19.         this.start();  
  20.     }  
  21.   
  22.     @Override  
  23.     public void run() {  
  24.         try {  
  25.             while (!shutdown) {  
  26.                 synchronized (this) {  
  27.                     wait(waitTime);  
  28.                     // 关闭失效的连接  
  29.                     connMgr.closeExpiredConnections();  
  30.                 }  
  31.             }  
  32.         } catch (InterruptedException ex) {  
  33.             // 结束  
  34.         }  
  35.     }  
  36.   
  37.     /** 
  38.      * 销毁释放资源 
  39.      */  
  40.     public void shutdown() {  
  41.         shutdown = true;  
  42.         synchronized (this) {  
  43.             notifyAll();  
  44.         }  
  45.     }  
  46. }  
重新部署一下,就可以在controller里实例化HttpDeal类并调用它的方法了。我的spring MVC整合了json,所以返回值是json数据,比如:

[plain]  view plain  copy
  1. [{"id":1,"type":"管理员","menu":"1,2,3"},{"id":2,"type":"操作员","menu":"1,2,"}]  
  2. [{"id":4,"attributes":null,"children":[],"text":"用户管理","pid":1,"url":"../user/getPage.do","title":null,"ptext":"系统管理"},{"id":5,"attributes":null,"children":[],"text":"部门管理","pid":1,"url":"../department/getPage.do","title":null,"ptext":"系统管理"},{"id":10,"attributes":null,"children":[],"text":"权限管理","pid":1,"url":"../userType/getPage.do","title":null,"ptext":"系统管理"}]  

可以通过我另一篇文章http://blog.csdn.net/u012116457/article/details/24371877里的方法将json转为map等。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值