spring MVC 管理HttpClient---实现在java中直接向Controller发送请求
在spring MVC中,大多数时候是由客户端的页面通过ajax等方式向controller发送请求,但有时候需要在java代码中直接向controller发送请求,这时可以使用HttpCilent实现。
首先用到的包是httpclient-4.3.5.jar和httpcore-4.3.2.jar
先看下面代码:
- package module.system.common;
- import java.io.IOException;
- import java.util.ArrayList;
- import java.util.HashMap;
- import java.util.List;
- import java.util.Map;
- import java.util.Set;
- import org.apache.http.NameValuePair;
- import org.apache.http.client.ClientProtocolException;
- import org.apache.http.client.entity.UrlEncodedFormEntity;
- import org.apache.http.client.methods.CloseableHttpResponse;
- import org.apache.http.client.methods.HttpGet;
- import org.apache.http.client.methods.HttpPost;
- import org.apache.http.impl.client.CloseableHttpClient;
- import org.apache.http.impl.client.HttpClients;
- import org.apache.http.message.BasicNameValuePair;
- import org.apache.http.util.EntityUtils;
- /**
- * 在java中处理http请求.
- * @author nagsh
- *
- */
- public class HttpDeal {
- /**
- * 处理get请求.
- * @param url 请求路径
- * @return json
- */
- public String get(String url){
- //实例化httpclient
- CloseableHttpClient httpclient = HttpClients.createDefault();
- //实例化get方法
- HttpGet httpget = new HttpGet(url);
- //请求结果
- CloseableHttpResponse response = null;
- String content ="";
- try {
- //执行get方法
- response = httpclient.execute(httpget);
- if(response.getStatusLine().getStatusCode()==200){
- content = EntityUtils.toString(response.getEntity(),"utf-8");
- System.out.println(content);
- }
- } catch (ClientProtocolException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- return content;
- }
- /**
- * 处理post请求.
- * @param url 请求路径
- * @param params 参数
- * @return json
- */
- public String post(String url,Map<String, String> params){
- //实例化httpClient
- CloseableHttpClient httpclient = HttpClients.createDefault();
- //实例化post方法
- HttpPost httpPost = new HttpPost(url);
- //处理参数
- List<NameValuePair> nvps = new ArrayList <NameValuePair>();
- Set<String> keySet = params.keySet();
- for(String key : keySet) {
- nvps.add(new BasicNameValuePair(key, params.get(key)));
- }
- //结果
- CloseableHttpResponse response = null;
- String content="";
- try {
- //提交的参数
- UrlEncodedFormEntity uefEntity = new UrlEncodedFormEntity(nvps, "UTF-8");
- //将参数给post方法
- httpPost.setEntity(uefEntity);
- //执行post方法
- response = httpclient.execute(httpPost);
- if(response.getStatusLine().getStatusCode()==200){
- content = EntityUtils.toString(response.getEntity(),"utf-8");
- System.out.println(content);
- }
- } catch (ClientProtocolException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- return content;
- }
- public static void main(String[] args) {
- HttpDeal hd = new HttpDeal();
- hd.get("http://localhost:8080/springMVC/userType/getAll.do");
- Map<String,String> map = new HashMap();
- map.put("id","1");
- hd.post("http://localhost:8080/springMVC/menu/getChildren.do",map);
- }
- }
这个类里的get和post方法分别可以实现get请求和post请求,如果单单在一个java测试类里边运行是没问题的,但在controller或jsp中调用,会抛异常。为什么呢?由于是在springMVC中,所以,我们应该把它交给spring来管理。
首先是:httpClient-servlet.xml
- <?xml version="1.0" encoding="UTF-8"?>
- <beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:context="http://www.springframework.org/schema/context"
- xmlns:p="http://www.springframework.org/schema/p"
- xmlns:aop="http://www.springframework.org/schema/aop"
- xmlns:tx="http://www.springframework.org/schema/tx"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
- http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
- 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
- http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">
- <!-- 配置占位符 -->
- <bean
- class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
- <property name="location" value="classpath:/httpclient.properties" />
- </bean>
- <!-- 定义httpclient连接池 -->
- <bean id="httpClientConnectionManager" class="org.apache.http.impl.conn.PoolingHttpClientConnectionManager" destroy-method="close">
- <!-- 设置连接总数 -->
- <property name="maxTotal" value="${http.pool.maxTotal}"></property>
- <!-- 设置每个地址的并发数 -->
- <property name="defaultMaxPerRoute" value="${http.pool.defaultMaxPerRoute}"></property>
- </bean>
- <!-- 定义 HttpClient工厂,这里使用HttpClientBuilder构建-->
- <bean id="httpClientBuilder" class="org.apache.http.impl.client.HttpClientBuilder" factory-method="create">
- <property name="connectionManager" ref="httpClientConnectionManager"></property>
- </bean>
- <!-- 得到httpClient的实例 -->
- <bean id="httpClient" factory-bean="httpClientBuilder" factory-method="build"/>
- <!-- 定期清理无效的连接 -->
- <bean class="module.system.common.IdleConnectionEvictor" destroy-method="shutdown">
- <constructor-arg index="0" ref="httpClientConnectionManager" />
- <!-- 间隔一分钟清理一次 -->
- <constructor-arg index="1" value="60000" />
- </bean>
- <!-- 定义requestConfig的工厂 -->
- <bean id="requestConfigBuilder" class="org.apache.http.client.config.RequestConfig.Builder">
- <!-- 从连接池中获取到连接的最长时间 -->
- <property name="connectionRequestTimeout" value="${http.request.connectionRequestTimeout}"/>
- <!-- 创建连接的最长时间 -->
- <property name="connectTimeout" value="${http.request.connectTimeout}"/>
- <!-- 数据传输的最长时间 -->
- <property name="socketTimeout" value="${http.request.socketTimeout}"/>
- <!-- 提交请求前测试连接是否可用 -->
- <property name="staleConnectionCheckEnabled" value="${http.request.staleConnectionCheckEnabled}"/>
- </bean>
- <!-- 得到requestConfig实例 -->
- <bean id="requestConfig" factory-bean="requestConfigBuilder" factory-method="build" />
- </beans>
httpclient.properties:
- #从连接池中获取到连接的最长时间
- http.request.connectionRequestTimeout=500
- #5000
- http.request.connectTimeout=5000
- #数据传输的最长时间
- http.request.socketTimeout=30000
- #提交请求前测试连接是否可用
- http.request.staleConnectionCheckEnabled=true
- #设置连接总数
- http.pool.maxTotal=200
- #设置每个地址的并发数
- http.pool.defaultMaxPerRoute=100
一个必须的类,几记得修改xml里的该类的路径:
- package module.system.common;
- import org.apache.http.conn.HttpClientConnectionManager;
- /**
- * 定期清理无效的http连接
- */
- public class IdleConnectionEvictor extends Thread {
- private final HttpClientConnectionManager connMgr;
- private Integer waitTime;
- private volatile boolean shutdown;
- public IdleConnectionEvictor(HttpClientConnectionManager connMgr,Integer waitTime) {
- this.connMgr = connMgr;
- this.waitTime = waitTime;
- this.start();
- }
- @Override
- public void run() {
- try {
- while (!shutdown) {
- synchronized (this) {
- wait(waitTime);
- // 关闭失效的连接
- connMgr.closeExpiredConnections();
- }
- }
- } catch (InterruptedException ex) {
- // 结束
- }
- }
- /**
- * 销毁释放资源
- */
- public void shutdown() {
- shutdown = true;
- synchronized (this) {
- notifyAll();
- }
- }
- }
重新部署一下,就可以在controller里实例化HttpDeal类并调用它的方法了。我的spring MVC整合了json,所以返回值是json数据,比如:
- [{"id":1,"type":"管理员","menu":"1,2,3"},{"id":2,"type":"操作员","menu":"1,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发送请求的更多相关文章
- Spring MVC普通类或工具类中调用service报空空指针的解决办法(调用service报java.lang.NullPointerException)
当我们在非Controller类中应用service的方法是会报空指针,如图: 这是因为Spring MVC普通类或工具类中调用service报空null的解决办法(调用service报java.la ...
- (4.1)Spring MVC执行原理和基于Java的配置过程
一.Spring MVC执行原理和基于Java配置的配置过程 (一)Spring MVC执行过程,大致为7步. 所有的请求都会经过Spring的一个单例的DispacherServlet. Dispa ...
- Spring MVC执行原理和基于Java的配置过程
一.Spring MVC执行原理和基于Java配置的配置过程 (一)Spring MVC执行过程,大致为7步. 所有的请求都会经过Spring的一个单例的DispacherServlet. Dispa ...
- spring mvc:内部资源视图解析器2(注解实现)@Controller/@RequestMapping
spring mvc:内部资源视图解析器2(注解实现) @Controller/@RequestMapping 访问地址: http://localhost:8080/guga2/hello/goo ...
- java中使HttpDelete可以发送body信息
java中使HttpDelete可以发送body信息RESTful api中用到了DELETE方法,android开发的同事遇到了问题,使用HttpDelete执行DELETE操作的时候,不能携带bo ...
- 使用Spring MVC,Mybatis框架等创建Java Web项目时各种前期准备的配置文件内容
1.pom.xml 首先,pom.xml文件,里面包含各种maven的依赖,代码如下: <project xmlns="http://maven.apache.org/POM/4.0. ...
- 【原创】Spring MVC项目搭建(使用Java配置)
一.使用Intellij idea,新建maven项目,选择maven-archetype-webapp. 二.在src/main下新建文件夹,命名为java,并标注为source folder. 三 ...
- Java内存管理-你真的理解Java中的数据类型吗(十)
勿在流沙筑高台,出来混迟早要还的. 做一个积极的人 编码.改bug.提升自己 我有一个乐园,面向编程,春暖花开! 作为Java程序员,Java 的数据类型这个是一定要知道的! 但是不管是那种数据类型最 ...
- Play framework框架中通过post方式发送请求
搞了好久这个最终还是在play官方文档中看见的发送请求的方式,国内好像很少有使用这个框架的,加之自己不是太愿意宣传,好东西总归是好东西,不说废话了. 在play中发送请求有两种常用的方式,一种get, ...
随机推荐
- 数据结构---栈C语言实现
#include <stdio.h> #include <stdlib.h> #define uchar unsigned char #define uint unsigned ...
- IOS空数据页面,网络加载失败以及重新登陆View的封装(不需要继承)
一.问题 对于B2C和B2B项目的开发者,可能会有一个订单列表为空,或者其他收藏页面为空,用户token失效,判断用户要重新登陆,以及后台服务错误等提示.本篇课文,看完大约10分钟. 原本自己不想写空 ...
- log4j日志的配置
在项目开发中,记录错误日志方便调试.便于发现系统运行过程中的错误.便于后期分析, 在java中,记录日志有很多种方式,比如说log4j log4j需要导入的包: commons-loggin.jar ...
- wamp 服务监控和启动
近日我的 wamp 莫名其妙的崩溃重启,apache 能自动起来, mysql 却悲剧了. 于是有了下面的wamp服务监控和启动的批处理文件 @echo off rem define loop tim ...
- 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 ...
- ORACLE之TO_DATE (转载)
转自 http://www.cnblogs.com/anran_guojianjun/archive/2009/09/11/1564535.html 一.在使用Oracle的to_date函数来做日期 ...
- JSON 的含义?
JSON 的全称是 JavaScript Object Notation,是一种轻量级的数据交换格式.JS ON 与 XML 具有相同的特性,例如易于人编写和阅读,易于机器生成和解析.但是 JSON ...
- access treeview读取数据表成树并与子窗体联动
Private Sub Form_Load()Dim i As IntegerDim rst As DAO.RecordsetSet rst = CurrentDb.OpenRecordset(&qu ...
- nslookup查询结果详解
nslookup可以指定查询的类型,可以查到DNS记录的生存时间还可以指定使用那个DNS服务器进行解释.在已安装TCP/IP协议的电脑上面均可以使用这个命令.主要用来诊断域名系统 (DNS) 基础结构 ...
- Pivotal开源基于PostgreSQL的数据库Greenplum
http://www.infoq.com/cn/news/2015/11/PostgreSQL-Pivotal 近日,Pivotal宣布开源大规模并行处理(MPP)数据库Greenplum,其架构是针 ...