httpclient与springmvc整合

来源:互联网 发布:mac版word怎么看字数 编辑:程序博客网 时间:2024/06/08 14:59

1、HttpClient的用法简介

     关于JavaScript跨域的请求,可以在后台使用HttpClient去请求,再把请求结果发回给前台。已解决JavaScript跨域访问的问题。

2、HttpClient与Spring的整合文件

     2.1 httpclient.properties的配置

[html] view plain copy
  1. #设置最大连接数  
  2. http.maxTotal=200  
  3. #设置每个主机的并发数  
  4. http.defaultMaxPerRoute=20  
  5.   
  6. #创建连接的最长时间  
  7. http.connectTimeout=1000  
  8. #从连接池中获取到连接的最长时间  
  9. http.connectionRequestTimeout=500  
  10. #数据传输的最长时间  
  11. http.socketTimeout=10000  
  12. #提交请求前测试连接是否可用  
  13. http.staleConnectionCheckEnabled=true  

     2.2 log4j.properties的配置

[html] view plain copy
  1. log4j.rootLogger=DEBUG,A1  
  2. log4j.logger.com.taotao = DEBUG  
  3. log4j.logger.org.mybatis = DEBUG  
  4.   
  5. log4j.appender.A1=org.apache.log4j.ConsoleAppender  
  6. log4j.appender.A1.layout=org.apache.log4j.PatternLayout  
  7. log4j.appender.A1.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss,SSS} [%t] [%c]-[%p] %m%n  

     2.3 bean-properties.xml的配置

[html] view plain copy
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"  
  4.     xmlns:context="http://www.springframework.org/schema/context"  
  5.     xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"  
  6.     xsi:schemaLocation="http://www.springframework.org/schema/beans    
  7.          http://www.springframework.org/schema/beans/spring-beans.xsd    
  8.          http://www.springframework.org/schema/context    
  9.          http://www.springframework.org/schema/context/spring-context.xsd    
  10.          http://www.springframework.org/schema/aop    
  11.          http://www.springframework.org/schema/aop/spring-aop.xsd    
  12.          http://www.springframework.org/schema/tx    
  13.          http://www.springframework.org/schema/tx/spring-tx.xsd">  
  14.     <!-- 使用spring自带的占位符替换功能 -->  
  15.     <bean  
  16.         class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  
  17.         <!-- 允许JVM参数覆盖 -->  
  18.         <property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />  
  19.         <!-- 忽略没有找到的资源文件 -->  
  20.         <property name="ignoreResourceNotFound" value="true" />  
  21.         <!-- 配置资源文件 -->  
  22.         <property name="locations">  
  23.             <list>  
  24.                 <value>classpath:httpclient.properties</value>  
  25.             </list>  
  26.         </property>  
  27.     </bean>  
  28.     <!--需要扫描的package -->  
  29.     <context:component-scan base-package="com.web.service" />  
  30. </beans>         

     2.4 bean-httpclient.xml的配置

[html] view plain copy
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"  
  4.     xmlns:context="http://www.springframework.org/schema/context"  
  5.     xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"  
  6.     xsi:schemaLocation="http://www.springframework.org/schema/beans    
  7.          http://www.springframework.org/schema/beans/spring-beans.xsd    
  8.          http://www.springframework.org/schema/context    
  9.          http://www.springframework.org/schema/context/spring-context.xsd    
  10.          http://www.springframework.org/schema/aop    
  11.          http://www.springframework.org/schema/aop/spring-aop.xsd    
  12.          http://www.springframework.org/schema/tx    
  13.          http://www.springframework.org/schema/tx/spring-tx.xsd">  
  14.   
  15.     <!--创建httpclient的连接池 -->  
  16.     <bean id="httpClientConnectionManager"  
  17.         class="org.apache.http.impl.conn.PoolingHttpClientConnectionManager"  
  18.         destroy-method="shutdown">  
  19.         <!-- 设置最大连接数 -->  
  20.         <property name="maxTotal" value="${http.maxTotal}" />  
  21.         <!-- 设置每个主机的并发数 -->  
  22.         <property name="defaultMaxPerRoute" value="${http.defaultMaxPerRoute}" />  
  23.     </bean>  
  24.   
  25.     <!-- 创建httpClient对象 -->  
  26.     <!-- httpClient是由HttpClientBuilder通过build方法创建,这个可以设置连接池 -->  
  27.     <!-- 1.创建HttpClientBuilder -->  
  28.     <bean id="httpClientBuilder" class="org.apache.http.impl.client.HttpClientBuilder">  
  29.         <!--设置连接池 -->  
  30.         <property name="connectionManager" ref="httpClientConnectionManager"></property>  
  31.     </bean>  
  32.     <!-- 2.创建httpClient -->  
  33.     <!-- 通过httpClientBulider得到httpClient对象,并且设置httpClient为多利模式 -->  
  34.     <!-- 要保证httpClient为多利,以为每次都是新的http请求 -->  
  35.     <bean id="httpClient" class="org.apache.http.impl.client.CloseableHttpClient"  
  36.         factory-bean="httpClientBuilder" factory-method="build" scope="prototype" />  
  37.   
  38.     <!-- 构造请求参数 -->  
  39.     <bean id="requestConfigBuilder" class="org.apache.http.client.config.RequestConfig.Builder">  
  40.         <!-- 创建连接的最长时间 -->  
  41.         <property name="connectTimeout" value="${http.connectTimeout}" />  
  42.         <!-- 从连接池中获取到连接的最长时间 -->  
  43.         <property name="connectionRequestTimeout" value="${http.connectionRequestTimeout}" />  
  44.         <!-- 数据传输的最长时间 -->  
  45.         <property name="socketTimeout" value="${http.socketTimeout}" />  
  46.         <!-- 提交请求前测试连接是否可用 -->  
  47.         <property name="staleConnectionCheckEnabled" value="${http.staleConnectionCheckEnabled}" />  
  48.     </bean>  
  49.     <bean id="requestConfig" class="org.apache.http.client.config.RequestConfig"  
  50.         factory-bean="requestConfigBuilder" factory-method="build" />  
  51.   
  52.   
  53.     <!--清理无效的http连接 -->  
  54.     <bean class="com.web.service.IdleConnectionEvictor"  
  55.         destroy-method="shutdown">  
  56.         <constructor-arg index="0" ref="httpClientConnectionManager"></constructor-arg>  
  57.     </bean>  
  58. </beans>         

3、 封装了HttpClient操作的HttpService.java的实现

[java] view plain copy
  1. import java.io.IOException;  
  2. import java.net.URI;  
  3. import java.net.URISyntaxException;  
  4. import java.util.ArrayList;  
  5. import java.util.List;  
  6. import java.util.Map;  
  7. import org.apache.http.NameValuePair;  
  8. import org.apache.http.client.ClientProtocolException;  
  9. import org.apache.http.client.config.RequestConfig;  
  10. import org.apache.http.client.entity.UrlEncodedFormEntity;  
  11. import org.apache.http.client.methods.CloseableHttpResponse;  
  12. import org.apache.http.client.methods.HttpGet;  
  13. import org.apache.http.client.methods.HttpPost;  
  14. import org.apache.http.client.utils.URIBuilder;  
  15. import org.apache.http.impl.client.CloseableHttpClient;  
  16. import org.apache.http.message.BasicNameValuePair;  
  17. import org.apache.http.util.EntityUtils;  
  18. import org.springframework.beans.factory.annotation.Autowired;  
  19. import org.springframework.stereotype.Service;  
  20.   
  21. @Service  
  22. public class HttpService {  
  23.   
  24.     // 创建Httpclient对象  
  25.     @Autowired(required = false)  
  26.     private CloseableHttpClient httpClient;  
  27.   
  28.     // 请求信息的配置  
  29.     @Autowired(required = false)  
  30.     private RequestConfig requestConfig;  
  31.   
  32.     /** 
  33.      * 执行Get请求 
  34.      *  
  35.      * @param url 
  36.      * @return 请求到的内容 
  37.      * @throws URISyntaxException 
  38.      * @throws IOException 
  39.      * @throws ClientProtocolException 
  40.      */  
  41.     public String doGet(String url) throws URISyntaxException,  
  42.             ClientProtocolException, IOException {  
  43.         return doGet(url, null);  
  44.     }  
  45.   
  46.     /** 
  47.      * 执行Get请求 
  48.      *  
  49.      * @param url 
  50.      * @param params 
  51.      *            请求中的参数 
  52.      * @return 请求到的内容 
  53.      * @throws URISyntaxException 
  54.      * @throws IOException 
  55.      * @throws ClientProtocolException 
  56.      */  
  57.     public String doGet(String url, Map<String, Object> params)  
  58.             throws URISyntaxException, ClientProtocolException, IOException {  
  59.         // 定义请求的参数  
  60.         URI uri = null;  
  61.         if (params != null) {  
  62.             URIBuilder builder = new URIBuilder(url);  
  63.             for (Map.Entry<String, Object> entry : params.entrySet()) {  
  64.                 builder.addParameter(entry.getKey(),  
  65.                         String.valueOf(entry.getValue()));  
  66.             }  
  67.             uri = builder.build();  
  68.         }  
  69.   
  70.         // 创建http GET请求  
  71.         HttpGet httpGet = null;  
  72.         if (uri != null) {  
  73.             httpGet = new HttpGet(uri);  
  74.         } else {  
  75.             httpGet = new HttpGet(url);  
  76.         }  
  77.         // 设置请求参数  
  78.         httpGet.setConfig(this.requestConfig);  
  79.   
  80.         // 请求的结果  
  81.         CloseableHttpResponse response = null;  
  82.         try {  
  83.             // 执行请求  
  84.             response = httpClient.execute(httpGet);  
  85.             // 判断返回状态是否为200  
  86.             if (response.getStatusLine().getStatusCode() == 200) {  
  87.                 // 获取服务端返回的数据,并返回  
  88.                 return EntityUtils.toString(response.getEntity(), "UTF-8");  
  89.             }  
  90.         } finally {  
  91.             if (response != null) {  
  92.                 response.close();  
  93.             }  
  94.         }  
  95.         return null;  
  96.     }  
  97.   
  98.     /** 
  99.      *  
  100.      * @param url 
  101.      * @param params 
  102.      *            请求中的参数 
  103.      * @return 请求到的内容 
  104.      * @throws URISyntaxException 
  105.      * @throws ClientProtocolException 
  106.      * @throws IOException 
  107.      */  
  108.     public String doPost(String url, Map<String, Object> params)  
  109.             throws URISyntaxException, ClientProtocolException, IOException {  
  110.         // 设置post参数  
  111.         List<NameValuePair> parameters = null;  
  112.         // 构造一个form表单式的实体  
  113.         UrlEncodedFormEntity formEntity = null;  
  114.   
  115.         // 定义请求的参数  
  116.         if (params != null) {  
  117.             // 设置post参数  
  118.             parameters = new ArrayList<NameValuePair>();  
  119.             for (Map.Entry<String, Object> entry : params.entrySet()) {  
  120.                 // 添加参数  
  121.                 parameters.add(new BasicNameValuePair(entry.getKey(), String  
  122.                         .valueOf(entry.getValue())));  
  123.             }  
  124.             // 构造一个form表单式的实体  
  125.             formEntity = new UrlEncodedFormEntity(parameters);  
  126.         }  
  127.   
  128.         // 创建http GET请求  
  129.         HttpPost httpPost = null;  
  130.         if (formEntity != null) {  
  131.             httpPost = new HttpPost(url);  
  132.             // 将请求实体设置到httpPost对象中  
  133.             httpPost.setEntity(formEntity);  
  134.             // 伪装浏览器请求  
  135.             httpPost.setHeader(  
  136.                     "User-Agent",  
  137.                     "Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36");  
  138.         } else {  
  139.             httpPost = new HttpPost(url);  
  140.             // 伪装浏览器请求  
  141.             httpPost.setHeader(  
  142.                     "User-Agent",  
  143.                     "Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36");  
  144.         }  
  145.         // 设置请求参数  
  146.         httpPost.setConfig(this.requestConfig);  
  147.   
  148.         // 请求的结果  
  149.         CloseableHttpResponse response = null;  
  150.         try {  
  151.             // 执行请求  
  152.             response = httpClient.execute(httpPost);  
  153.             // 判断返回状态是否为200  
  154.             if (response.getStatusLine().getStatusCode() == 200) {  
  155.                 // 获取服务端返回的数据,并返回  
  156.                 return EntityUtils.toString(response.getEntity(), "UTF-8");  
  157.             }  
  158.         } finally {  
  159.             if (response != null) {  
  160.                 response.close();  
  161.             }  
  162.         }  
  163.         return null;  
  164.     }  
  165.   
  166.     /** 
  167.      *  
  168.      * @param url 
  169.      * @param params 
  170.      *            请求中的参数 
  171.      * @return 请求到的内容 
  172.      * @throws URISyntaxException 
  173.      * @throws ClientProtocolException 
  174.      * @throws IOException 
  175.      */  
  176.     public String doPost(String url) throws URISyntaxException,  
  177.             ClientProtocolException, IOException {  
  178.         return doPost(url, null);  
  179.     }  
  180. }  
@Autowired(required = false)表示的含义是,spring容器里面有这个bean就注入,没有就不注入。

4、 用于清除无效请求IdleConnectionEvictor.java的实现

[java] view plain copy
  1. import org.apache.http.conn.HttpClientConnectionManager;  
  2.   
  3. //关闭连接池的无效链接  
  4. public class IdleConnectionEvictor extends Thread {  
  5.   
  6.     private final HttpClientConnectionManager connMgr;  
  7.   
  8.     private volatile boolean shutdown;  
  9.   
  10.     public IdleConnectionEvictor(HttpClientConnectionManager connMgr) {  
  11.         this.connMgr = connMgr;  
  12.         this.start();// 启动线程  
  13.     }  
  14.   
  15.     @Override  
  16.     public void run() {  
  17.         try {  
  18.             while (!shutdown) {  
  19.                 synchronized (this) {  
  20.                     // 每隔5秒执行一个,关闭失效的http连接  
  21.                     wait(5000);  
  22.                     // 关闭失效的连接  
  23.                     connMgr.closeExpiredConnections();  
  24.                 }  
  25.             }  
  26.         } catch (InterruptedException ex) {  
  27.             // 结束  
  28.         }  
  29.     }  
  30.   
  31.     public void shutdown() {  
  32.         shutdown = true;  
  33.         synchronized (this) {  
  34.             notifyAll();  
  35.         }  
  36.     }  
  37.   
  38. }  

5、 测试代码

[java] view plain copy
  1. public class TestApp {  
  2.     public static void main(String[] args) {  
  3.         ApplicationContext context = new ClassPathXmlApplicationContext(  
  4.                 "classpath:spring/bean-*.xml");  
  5.         System.out.println(context);  
  6.   
  7.         HttpService httpService = context.getBean("httpService",  
  8.                 HttpService.class);  
  9.         System.out.println(httpService);  
  10.         try {  
  11.             // Map<String, String> maps = new HashMap<String, String>();  
  12.             // maps.put("wd", "java");  
  13.             // String string = httpService.doGet("http://www.baidu.com/s");  
  14.             // System.out.println(string);  
  15.   
  16.             Map<String, Object> maps = new HashMap<String, Object>();  
  17.             maps.put("wd""java");  
  18.             String string = httpService.doPost(  
  19.                     "http://localhost:8080/ssss/HaHaServlet", maps);  
  20.             System.out.println(string);  
  21.   
  22.         } catch (Exception e) {  
  23.             e.printStackTrace();  
  24.         }  
  25.   
  26.     }  
  27. }  

6、源码下载

https://pan.baidu.com/s/1o7HF8MY


原创粉丝点击