zoukankan      html  css  js  c++  java
  • spring整合http

    本文版权归作者所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接出处:https://blog.csdn.net/qq_3076499,否则保留追究法律责任的权利。 如果文中有什么错误,欢迎指出。以免更多的人被误导。如果对您有帮助 ,请多多支持.多少都是您的心意与支持,再次感谢!!!

    spring框架是一个非常强大的框架这里就不多说了,那么主要是介绍spring与httpclient的整合集成。
    一、简介
    HttpClient是Apache Jakarta Common下的子项目,用来提供高效的、最新的、功能丰富的支持HTTP协议的客户端编程工具包,并且它支持HTTP协议最新的版本和建议。HttpClient已经应用在很多的项目中,比如Apache Jakarta上很著名的另外两个开源项目Cactus和HTMLUnit都使用了HttpClient。

    下载地址: http://hc.apache.org/downloads.cgi

    二、特性
    1. 基于标准、纯净的java语言。实现了Http1.0和Http1.1

    2. 以可扩展的面向对象的结构实现了Http全部的方法(GET, POST, PUT, DELETE, HEAD, OPTIONS, and TRACE)。

    3. 支持HTTPS协议。

    4. 通过Http代理建立透明的连接。

    5. 利用CONNECT方法通过Http代理建立隧道的https连接。

    6. Basic, Digest, NTLMv1, NTLMv2, NTLM2 Session, SNPNEGO/Kerberos认证方案。

    7. 插件式的自定义认证方案。

    8. 便携可靠的套接字工厂使它更容易的使用第三方解决方案。

    9. 连接管理器支持多线程应用。支持设置最大连接数,同时支持设置每个主机的最大连接数,发现并关闭过期的连接。

    10. 自动处理Set-Cookie中的Cookie。

    11. 插件式的自定义Cookie策略。

    12. Request的输出流可以避免流中内容直接缓冲到socket服务器。

    13. Response的输入流可以有效的从socket服务器直接读取相应内容。

    14. 在http1.0和http1.1中利用KeepAlive保持持久连接。

    15. 直接获取服务器发送的response code和 headers。

    16. 设置连接超时的能力。

    17. 实验性的支持http1.1 response caching。

    18. 源代码基于Apache License 可免费获取。

    三、使用方法
    使用HttpClient发送请求、接收响应很简单,一般需要如下几步即可。

    1. 创建HttpClient对象。

    2. 创建请求方法的实例,并指定请求URL。如果需要发送GET请求,创建HttpGet对象;如果需要发送POST请求,创建HttpPost对象。

    3. 如果需要发送请求参数,可调用HttpGet、HttpPost共同的setParams(HetpParams params)方法来添加请求参数;对于HttpPost对象而言,也可调用setEntity(HttpEntity entity)方法来设置请求参数。

    4. 调用HttpClient对象的execute(HttpUriRequest request)发送请求,该方法返回一个HttpResponse。

    5. 调用HttpResponse的getAllHeaders()、getHeaders(String name)等方法可获取服务器的响应头;调用HttpResponse的getEntity()方法可获取HttpEntity对象,该对象包装了服务器的响应内容。程序可通过该对象获取服务器的响应内容。

    6. 释放连接。无论执行方法是否成功,都必须释放连接

    get方式

    /** 
         * 发送 get请求 
         */   
        public void get() {   
            CloseableHttpClient httpclient = HttpClients.createDefault();   
            try {   
                // 创建httpget.     
                HttpGet httpget = new HttpGet("http://www.baidu.com/");   
                System.out.println("executing request " + httpget.getURI());   
                // 执行get请求.     
                CloseableHttpResponse response = httpclient.execute(httpget);   
                try {   
                    // 获取响应实体     
                    HttpEntity entity = response.getEntity();   
                    System.out.println("--------------------------------------");   
                    // 打印响应状态     
                    System.out.println(response.getStatusLine());   
                    if (entity != null) {   
                        // 打印响应内容长度     
                        System.out.println("Response content length: " + entity.getContentLength());   
                        // 打印响应内容     
                        System.out.println("Response content: " + EntityUtils.toString(entity));   
                    }   
                    System.out.println("------------------------------------");   
                } finally {   
                    response.close();   
                }   
            } catch (ClientProtocolException e) {   
                e.printStackTrace();   
            } catch (ParseException e) {   
                e.printStackTrace();   
            } catch (IOException e) {   
                e.printStackTrace();   
            } finally {   
                // 关闭连接,释放资源     
                try {   
                    httpclient.close();   
                } catch (IOException e) {   
                    e.printStackTrace();   
                }   
            }   
        }   
    post方式

    /** 
         * 发送 post请求访问本地应用并根据传递参数不同返回不同结果 
         */   
        public void post() {   
            // 创建默认的httpClient实例.     
            CloseableHttpClient httpclient = HttpClients.createDefault();   
            // 创建httppost     
            HttpPost httppost = new HttpPost("http://localhost:8080/myDemo/Ajax/serivceJ.action");   
            // 创建参数队列     
            List<NameValuePair> formparams = new ArrayList<NameValuePair>();   
            formparams.add(new BasicNameValuePair("type", "house"));   
            UrlEncodedFormEntity uefEntity;   
            try {   
                uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");   
                httppost.setEntity(uefEntity);   
                System.out.println("executing request " + httppost.getURI());   
                CloseableHttpResponse response = httpclient.execute(httppost);   
                try {   
                    HttpEntity entity = response.getEntity();   
                    if (entity != null) {   
                        System.out.println("--------------------------------------");   
                        System.out.println("Response content: " + EntityUtils.toString(entity, "UTF-8"));   
                        System.out.println("--------------------------------------");   
                    }   
                } finally {   
                    response.close();   
                }   
            } catch (ClientProtocolException e) {   
                e.printStackTrace();   
            } catch (UnsupportedEncodingException e1) {   
                e1.printStackTrace();   
            } catch (IOException e) {   
                e.printStackTrace();   
            } finally {   
                // 关闭连接,释放资源     
                try {   
                    httpclient.close();   
                } catch (IOException e) {   
                    e.printStackTrace();   
                }   
            }   
        }   
    好了,到此,以上简单的httpclient介绍与实体。那么接下来是介绍spring与httpclient的整合集成。

    1,创建一个maven项目。往pom中引入httpclient所依赖的jar包,具体如下:

    1引入jar包

    <dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.2</version>
    </dependency>
    2.spring和httpClient整合配置文件。这个很重要请看仔细。

    <?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-4.0.xsd
    http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">


    <!-- 定义连接管理器 -->
    <bean id="connectionManager"
    class="org.apache.http.impl.conn.PoolingHttpClientConnectionManager">
    <!-- 最大连接数 -->
    <property name="maxTotal" value="${http.maxTotal}" />
    <property name="defaultMaxPerRoute" value="${http.defaultMaxPerRoute}" />
    </bean>


    <!-- 定义Httpclient构造器 -->
    <bean id="httpClientBuilder" class="org.apache.http.impl.client.HttpClientBuilder">
    <property name="connectionManager" ref="connectionManager" />
    </bean>
    <!--定义httpClient对象,该bean一定是多例的 -->
    <bean id="httpClient" class="org.apache.http.impl.client.CloseableHttpClient"
    factory-bean="httpClientBuilder" factory-method="build" scope="prototype"></bean>
    <!--定义requestConfig构建器 -->
    <bean id="requestConfigBuilder" class="org.apache.http.client.config.RequestConfig.Builder">
    <!--设置创建连接的最长时间 -->
    <property name="connectTimeout" value="${http.connectTimeout}" />
    <!--从连接池中获取到连接的最长时间 -->
    <property name="connectionRequestTimeout" value="${http.connectionRequestTimeout}" />
    <!--数据传输的最长时间 -->
    <property name="socketTimeout" value="${http.socketTimeout}" />
    </bean>
    <!--请求参数对象 -->
    <bean class="org.apache.http.client.config.RequestConfig"
    factory-bean="requestConfigBuilder" factory-method="build"></bean>
    <!--定期清理无效连接 ,com.baidu.utils这个链接可以填写你自己不需要的无效链接-->
    <bean class="com.baidu.utils.httpclient.IdleConnectionEvictor"
    destroy-method="shutdown">
    <constructor-arg index="0" ref="connectionManager" />

    </bean>

    </beans>

    3.httpclient.properties的配置文件


    #设置连接总数  
    http.maxTotal=500  
    #设置每个主机最大的并发数  
    http.defaultMaxPerRoute=100  
    #设置创建连接的最长时间  
    http.connectTimeout=2000  
    #从连接池中获取到连接的最长时间  
    http.connectionRequestTimeout=500  
    #数据传输的最长时间  
    http.socketTimeout=6000  
    #空闲时间(用于定期清理空闲连接)  
    http.maxIdleTime = 1</span>  
    #检测连接是否正确
    http.staleConnectionCheckEnabled=true
    到这里,那么spring与httpclient的整合集成就好了。但通常在企业中,我们是需要把httpclient封装成我们常用的工具。因在系统之间的调用,不仅是一个系统需要用到,很多系统都需要这个httpclient。所以这里也相应的整合封装成工具,供参考。

    一:httpclient封装的工具类,具体代码如下:

    package com.utils.httpclient;


    import java.io.IOException;
    import java.net.URISyntaxException;
    import java.nio.charset.Charset;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Map;


    import org.apache.http.NameValuePair;
    import org.apache.http.client.ClientProtocolException;
    import org.apache.http.client.config.RequestConfig;
    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.client.utils.URIBuilder;
    import org.apache.http.entity.ContentType;
    import org.apache.http.entity.StringEntity;
    import org.apache.http.impl.client.CloseableHttpClient;
    import org.apache.http.message.BasicNameValuePair;
    import org.apache.http.util.EntityUtils;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;


    /**
     * httpclient 常用操作的 工具类
     * 
     * @author Administrator
     *
     */
    @Service
    public class ApiService {  
        @Autowired  
        private CloseableHttpClient httpClient;  
        @Autowired  
        private RequestConfig requestConfig;  
      
        /** 
         * 执行get请求,200返回响应内容,其他状态码返回null 
         * 
         * @param url 
         * @return 
         * @throws IOException 
         */  
        public String doGet(String url) throws IOException {  
            //创建httpClient对象  
            CloseableHttpResponse response = null;  
            HttpGet httpGet = new HttpGet(url);  
            //设置请求参数  
            httpGet.setConfig(requestConfig);  
            try {  
                //执行请求  
                response = httpClient.execute(httpGet);  
                //判断返回状态码是否为200  
                if (response.getStatusLine().getStatusCode() == 200) {  
                    return EntityUtils.toString(response.getEntity(), "UTF-8");  
                }  
            } finally {  
                if (response != null) {  
                    response.close();  
                }  
            }  
            return null;  
        }  
      
        /** 
         * 执行带有参数的get请求 
         * 
         * @param url 
         * @param paramMap 
         * @return 
         * @throws IOException 
         * @throws URISyntaxException 
         */  
        public String doGet(String url, Map<String, String> paramMap) throws IOException, URISyntaxException {  
            URIBuilder builder = new URIBuilder(url);  
            for (String s : paramMap.keySet()) {  
                builder.addParameter(s, paramMap.get(s));  
            }  
            return doGet(builder.build().toString());  
        }  
      
        /** 
         * 执行post请求 
         * 
         * @param url 
         * @param paramMap 
         * @return 
         * @throws IOException 
         */  
        public HttpResult doPost(String url, Map<String, String> paramMap) throws IOException {  
            HttpPost httpPost = new HttpPost(url);  
            //设置请求参数  
            httpPost.setConfig(requestConfig);  
            if (paramMap != null) {  
                List<NameValuePair> parameters = new ArrayList<NameValuePair>();  
                for (String s : paramMap.keySet()) {  
                    parameters.add(new BasicNameValuePair(s, paramMap.get(s)));  
                }  
                //构建一个form表单式的实体  
                UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(parameters, Charset.forName("UTF-8"));  
                //将请求实体放入到httpPost中  
                httpPost.setEntity(formEntity);  
            }  
            //创建httpClient对象  
            CloseableHttpResponse response = null;  
            try {  
                //执行请求  
                response = httpClient.execute(httpPost);  
                return new HttpResult(response.getStatusLine().getStatusCode(), EntityUtils.toString(response.getEntity()));  
            } finally {  
                if (response != null) {  
                    response.close();  
                }  
            }  
        }  
      
        /** 
         * 执行post请求 
         * 
         * @param url 
         * @return 
         * @throws IOException 
         */  
        public HttpResult doPost(String url) throws IOException {  
            return doPost(url, null);  
        }  
      
      
        /** 
         * 提交json数据 
         * 
         * @param url 
         * @param json 
         * @return 
         * @throws ClientProtocolException 
         * @throws IOException 
         */  
        public HttpResult doPostJson(String url, String json) throws ClientProtocolException, IOException {  
            // 创建http POST请求  
            HttpPost httpPost = new HttpPost(url);  
            httpPost.setConfig(this.requestConfig);  
      
            if (json != null) {  
                // 构造一个请求实体  
                StringEntity stringEntity = new StringEntity(json, ContentType.APPLICATION_JSON);  
                // 将请求实体设置到httpPost对象中  
                httpPost.setEntity(stringEntity);  
            }  
            CloseableHttpResponse response = null;  
            try {  
                // 执行请求  
                response = this.httpClient.execute(httpPost);  
                return new HttpResult(response.getStatusLine().getStatusCode(),  
                        EntityUtils.toString(response.getEntity(), "UTF-8"));  
            } finally {  
                if (response != null) {  
                    response.close();  
                }  
            }  
        }  

    }

    二:http执行post请求返回的实体封装类,具体代码如下:

    package com.utils.httpclient;
    public class HttpResult {
    //状态码
            private Integer statusCode;
            //返回数据
            private String content;
            
            public HttpResult() {
                    
            }


            public HttpResult(Integer statusCode, String content) {
                    this.statusCode = statusCode;
                    this.content = content;
            }


            public Integer getStatusCode() {
                    return statusCode;
            }


            public void setStatusCode(Integer statusCode) {
                    this.statusCode = statusCode;
            }


            public String getContent() {
                    return content;
            }


            public void setContent(String content) {
                    this.content = content;
            }
            
    }

    三:使用一个单独的线程完成连接池中的无效链接的清理,具体代码如下:

    package com.utils.httpclient;


    import org.apache.http.conn.HttpClientConnectionManager;


    public class IdleConnectionEvictor extends Thread {


        private final HttpClientConnectionManager connMgr;


        private volatile boolean shutdown;


        public IdleConnectionEvictor(HttpClientConnectionManager connMgr) {
            this.connMgr = connMgr;
            //启动时开启线程
            this.start();
        }


        @Override
        public void run() {
            try {
                while (!shutdown) {
                    synchronized (this) {
                        wait(5000);
                        // 关闭失效的连接
                        connMgr.closeExpiredConnections();
                    }
                }
            } catch (InterruptedException ex) {
                // 结束
            }
        }


        public void shutdown() {
            shutdown = true;
            synchronized (this) {
                notifyAll();
            }
        }

    }

    Ok,到此,整个封装类也弄好了。如果,你还是没有明白,代码链接下载地址:https://github.com/oneboat


    本文版权归作者所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接出处:https://blog.csdn.net/qq_3076499,否则保留追究法律责任的权利。 如果文中有什么错误,欢迎指出。以免更多的人被误导。如果对您有帮助 ,请多多支持.多少都是您的心意与支持,再次感谢!!!

    /** 
         * 发送 get请求 
         */   
        public void get() {   
            CloseableHttpClient httpclient = HttpClients.createDefault();   
            try {   
                // 创建httpget.     
                HttpGet httpget = new HttpGet("http://www.baidu.com/");   
                System.out.println("executing request " + httpget.getURI());   
                // 执行get请求.     
                CloseableHttpResponse response = httpclient.execute(httpget);   
                try {   
                    // 获取响应实体     
                    HttpEntity entity = response.getEntity();   
                    System.out.println("--------------------------------------");   
                    // 打印响应状态     
                    System.out.println(response.getStatusLine());   
                    if (entity != null) {   
                        // 打印响应内容长度     
                        System.out.println("Response content length: " + entity.getContentLength());   
                        // 打印响应内容     
                        System.out.println("Response content: " + EntityUtils.toString(entity));   
                    }   
                    System.out.println("------------------------------------");   
                } finally {   
                    response.close();   
                }   
            } catch (ClientProtocolException e) {   
                e.printStackTrace();   
            } catch (ParseException e) {   
                e.printStackTrace();   
            } catch (IOException e) {   
                e.printStackTrace();   
            } finally {   
                // 关闭连接,释放资源     
                try {   
                    httpclient.close();   
                } catch (IOException e) {   
                    e.printStackTrace();   
                }   
            }   
        }   

  • 相关阅读:
    java 泛型 类型作为参量 Class<T> transform
    面向对象的类方法只具有命名空间的作用
    编程语言沉思录—编程语言的体系结构
    类型约束的作用
    函数重载、多态与型变
    函数类型与型变
    型变(逆变)函数
    scala 型变
    泛型编程的几个关键概念
    泛型是包含类型参数的抽象类型—类型构造器
  • 原文地址:https://www.cnblogs.com/h-c-g/p/10732133.html
Copyright © 2011-2022 走看看