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

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

先看下面代码:

  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. * 在java中处理http请求.
  23. * @author nagsh
  24. *
  25. */
  26. public class HttpDeal {
  27. /**
  28. * 处理get请求.
  29. * @param url 请求路径
  30. * @return json
  31. */
  32. public String get(String url){
  33. //实例化httpclient
  34. CloseableHttpClient httpclient = HttpClients.createDefault();
  35. //实例化get方法
  36. HttpGet httpget = new HttpGet(url);
  37. //请求结果
  38. CloseableHttpResponse response = null;
  39. String content ="";
  40. try {
  41. //执行get方法
  42. response = httpclient.execute(httpget);
  43. if(response.getStatusLine().getStatusCode()==200){
  44. content = EntityUtils.toString(response.getEntity(),"utf-8");
  45. System.out.println(content);
  46. }
  47. } catch (ClientProtocolException e) {
  48. e.printStackTrace();
  49. } catch (IOException e) {
  50. e.printStackTrace();
  51. }
  52. return content;
  53. }
  54. /**
  55. * 处理post请求.
  56. * @param url 请求路径
  57. * @param params 参数
  58. * @return json
  59. */
  60. public String post(String url,Map<String, String> params){
  61. //实例化httpClient
  62. CloseableHttpClient httpclient = HttpClients.createDefault();
  63. //实例化post方法
  64. HttpPost httpPost = new HttpPost(url);
  65. //处理参数
  66. List<NameValuePair> nvps = new ArrayList <NameValuePair>();
  67. Set<String> keySet = params.keySet();
  68. for(String key : keySet) {
  69. nvps.add(new BasicNameValuePair(key, params.get(key)));
  70. }
  71. //结果
  72. CloseableHttpResponse response = null;
  73. String content="";
  74. try {
  75. //提交的参数
  76. UrlEncodedFormEntity uefEntity = new UrlEncodedFormEntity(nvps, "UTF-8");
  77. //将参数给post方法
  78. httpPost.setEntity(uefEntity);
  79. //执行post方法
  80. response = httpclient.execute(httpPost);
  81. if(response.getStatusLine().getStatusCode()==200){
  82. content = EntityUtils.toString(response.getEntity(),"utf-8");
  83. System.out.println(content);
  84. }
  85. } catch (ClientProtocolException e) {
  86. e.printStackTrace();
  87. } catch (IOException e) {
  88. e.printStackTrace();
  89. }
  90. return content;
  91. }
  92. public static void main(String[] args) {
  93. HttpDeal hd = new HttpDeal();
  94. hd.get("http://localhost:8080/springMVC/userType/getAll.do");
  95. Map<String,String> map = new HashMap();
  96. map.put("id","1");
  97. hd.post("http://localhost:8080/springMVC/menu/getChildren.do",map);
  98. }
  99.  
  100. }

这个类里的get和post方法分别可以实现get请求和post请求,如果单单在一个java测试类里边运行是没问题的,但在controller或jsp中调用,会抛异常。为什么呢?由于是在springMVC中,所以,我们应该把它交给spring来管理。

首先是:httpClient-servlet.xml

  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. </beans>

httpclient.properties:

  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里的该类的路径:

  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数据,比如:

  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等。

版权声明:本文为博主原创文章,未经博主允许不得转载。

spring MVC 管理HttpClient---实现在java中直接向Controller发送请求的更多相关文章

  1. Spring MVC普通类或工具类中调用service报空空指针的解决办法(调用service报java.lang.NullPointerException)

    当我们在非Controller类中应用service的方法是会报空指针,如图: 这是因为Spring MVC普通类或工具类中调用service报空null的解决办法(调用service报java.la ...

  2. (4.1)Spring MVC执行原理和基于Java的配置过程

    一.Spring MVC执行原理和基于Java配置的配置过程 (一)Spring MVC执行过程,大致为7步. 所有的请求都会经过Spring的一个单例的DispacherServlet. Dispa ...

  3. Spring MVC执行原理和基于Java的配置过程

    一.Spring MVC执行原理和基于Java配置的配置过程 (一)Spring MVC执行过程,大致为7步. 所有的请求都会经过Spring的一个单例的DispacherServlet. Dispa ...

  4. spring mvc:内部资源视图解析器2(注解实现)@Controller/@RequestMapping

    spring mvc:内部资源视图解析器2(注解实现)  @Controller/@RequestMapping 访问地址: http://localhost:8080/guga2/hello/goo ...

  5. java中使HttpDelete可以发送body信息

    java中使HttpDelete可以发送body信息RESTful api中用到了DELETE方法,android开发的同事遇到了问题,使用HttpDelete执行DELETE操作的时候,不能携带bo ...

  6. 使用Spring MVC,Mybatis框架等创建Java Web项目时各种前期准备的配置文件内容

    1.pom.xml 首先,pom.xml文件,里面包含各种maven的依赖,代码如下: <project xmlns="http://maven.apache.org/POM/4.0. ...

  7. 【原创】Spring MVC项目搭建(使用Java配置)

    一.使用Intellij idea,新建maven项目,选择maven-archetype-webapp. 二.在src/main下新建文件夹,命名为java,并标注为source folder. 三 ...

  8. Java内存管理-你真的理解Java中的数据类型吗(十)

    勿在流沙筑高台,出来混迟早要还的. 做一个积极的人 编码.改bug.提升自己 我有一个乐园,面向编程,春暖花开! 作为Java程序员,Java 的数据类型这个是一定要知道的! 但是不管是那种数据类型最 ...

  9. Play framework框架中通过post方式发送请求

    搞了好久这个最终还是在play官方文档中看见的发送请求的方式,国内好像很少有使用这个框架的,加之自己不是太愿意宣传,好东西总归是好东西,不说废话了. 在play中发送请求有两种常用的方式,一种get, ...

随机推荐

  1. 数据结构---栈C语言实现

    #include <stdio.h> #include <stdlib.h> #define uchar unsigned char #define uint unsigned ...

  2. IOS空数据页面,网络加载失败以及重新登陆View的封装(不需要继承)

    一.问题 对于B2C和B2B项目的开发者,可能会有一个订单列表为空,或者其他收藏页面为空,用户token失效,判断用户要重新登陆,以及后台服务错误等提示.本篇课文,看完大约10分钟. 原本自己不想写空 ...

  3. log4j日志的配置

    在项目开发中,记录错误日志方便调试.便于发现系统运行过程中的错误.便于后期分析, 在java中,记录日志有很多种方式,比如说log4j log4j需要导入的包: commons-loggin.jar ...

  4. wamp 服务监控和启动

    近日我的 wamp 莫名其妙的崩溃重启,apache 能自动起来, mysql 却悲剧了. 于是有了下面的wamp服务监控和启动的批处理文件 @echo off rem define loop tim ...

  5. same tree(判断两颗二叉树是否相等)

    Input: 1 1 / \ / \ 2 3 2 3 [1,2,3], [1,2,3] Output: true Example 2: Input: 1 1 / \ 2 2 [1,2], [1,nul ...

  6. ORACLE之TO_DATE (转载)

    转自 http://www.cnblogs.com/anran_guojianjun/archive/2009/09/11/1564535.html 一.在使用Oracle的to_date函数来做日期 ...

  7. JSON 的含义?

    JSON 的全称是 JavaScript Object Notation,是一种轻量级的数据交换格式.JS ON 与 XML 具有相同的特性,例如易于人编写和阅读,易于机器生成和解析.但是 JSON ...

  8. access treeview读取数据表成树并与子窗体联动

    Private Sub Form_Load()Dim i As IntegerDim rst As DAO.RecordsetSet rst = CurrentDb.OpenRecordset(&qu ...

  9. nslookup查询结果详解

    nslookup可以指定查询的类型,可以查到DNS记录的生存时间还可以指定使用那个DNS服务器进行解释.在已安装TCP/IP协议的电脑上面均可以使用这个命令.主要用来诊断域名系统 (DNS) 基础结构 ...

  10. Pivotal开源基于PostgreSQL的数据库Greenplum

    http://www.infoq.com/cn/news/2015/11/PostgreSQL-Pivotal 近日,Pivotal宣布开源大规模并行处理(MPP)数据库Greenplum,其架构是针 ...