applicationContext-httpclient.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">
<!--引入外部配置文件  由于后期可能会引入多个配置文件 所以采用list的形式  -->
    <bean id="propertyPlaceholder" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <list>
    <value>classpath:/property/httpclient.properties</value>
            </list>
        </property>
    </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="com.jt.common.util.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=
#
http.request.connectTimeout=
#数据传输的最长时间
http.request.socketTimeout=
#提交请求前测试连接是否可用
http.request.staleConnectionCheckEnabled=true

#设置连接总数
http.pool.maxTotal=
#设置每个地址的并发数
http.pool.defaultMaxPerRoute=

HttpClientService.java

package com.jt.common.service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.NameValuePair;
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.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

@Service
public class HttpClientService {

    private static final Logger LOGGER = LoggerFactory.getLogger(HttpClientService.class);

    @Autowired(required=false)
    private CloseableHttpClient httpClient;

    @Autowired(required=false)
    private RequestConfig requestConfig;

    /**
     * 说明:
     *      请求方式:Get和POST请求
     *      参数如何添加:
     *         http://www.jd.com/add?id=1&name=2
     *   参数进行封装:
     *   如果用户需要传递参数,则通过指定的方法进行调用即可.
     *   Map<String,String>类型
     *
     *   /*url  = url + "?";

                //www.baidu.com?id=1&name=tom&
                for (Map.Entry<String, String> entry: params.entrySet()) {

                    url  = url + entry.getKey() + "=" + entry.getValue() + "&";
                }
                url = url.substring(0, url.length()-1);
      */

    public String doGet(String url,Map<String,String> params,String charset){

        String result = null; //访问服务端程序时回传的JSON数据

        //判断字符集编码是否为null,如果为null设定默认字符集
        if(StringUtils.isEmpty(charset)){

            charset = "UTF-8";
        }

        try {
            //判断参数是否为null
            if(params != null){
                URIBuilder builder = new URIBuilder(url);
                for (Map.Entry<String,String> entry : params.entrySet()) {

                    builder.addParameter(entry.getKey(),entry.getValue());
                }
                //自动的拼接?和&符  http://www.baidu.com?id=1&name=tom
                url = builder.build().toString();

            }

            //System.out.println("访问的请求:" + url);
            //定义请求的类型
            HttpGet httpGet = new HttpGet(url);
            httpGet.setConfig(requestConfig);

            //通过httpClient发送请求
            CloseableHttpResponse httpResponse =
                    httpClient.execute(httpGet);

            if(httpResponse.getStatusLine().getStatusCode() == 200){
                //获取返回值数据
                result =
                EntityUtils.toString(httpResponse.getEntity(),charset);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }

    public String doGet(String url,Map<String,String> params){

        return doGet(url, params, null);
    }

    public String doGet(String url){

        return doGet(url, null, null) ;
    }

    //实现httpClient中的post请求
    public String doPost(String url,Map<String,String> params,String charset){

        String result = null;
        //判断字符集编码
        if(StringUtils.isEmpty(charset)){

            charset = "UTF-8";
        }

        /**
         * 2.需要先创建请求对象
         *      2.1创建表单实体对象封装参数.
         *   2.2将表单对象保存到Post对象中
         *   2.3之后发起请求
         */
        HttpPost httpPost = new HttpPost(url);
        httpPost.setConfig(requestConfig);

        try {
            //判断是否有参数
            if(params != null){
                List<NameValuePair> parameters = new ArrayList<NameValuePair>();

                //获取用户传递的数据
                for (Map.Entry<String,String> entry: params.entrySet()) {
                    BasicNameValuePair pair =
                new BasicNameValuePair(entry.getKey(), entry.getValue());
                    parameters.add(pair);
                }
                //创建表单实体对象
                UrlEncodedFormEntity formEntity =
                        new UrlEncodedFormEntity(parameters,charset);

                //将请求实体添加到请求对象中
                httpPost.setEntity(formEntity);
            }

            //实现post请求
            CloseableHttpResponse httpResponse =
            httpClient.execute(httpPost);

            if(httpResponse.getStatusLine().getStatusCode() == 200){

                result = EntityUtils.toString(httpResponse.getEntity(),charset);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }

    public String doPost(String url,Map<String,String> params){

        return doPost(url, params, null);
    }

    public String doPost(String url){

        return doPost(url, null, null);
    }
}

httpclient的封装完整版的更多相关文章

  1. C# .NET更智能的数据库操作的封装完整版(重构)

    前述: 第一次发表文章,不过是对数据库简单的封装,主要是阐述下思路.那么在上篇文章,在大家的指导下和提出意见,并自己对代码进行了思考.在这两天我重构了新的框架,我觉得我写的可以称得上框架,为什么?请大 ...

  2. rip路由协议 细节分析及实例配置【完整版】

    rip路由协议 细节分析及实例配置[完整版] RIP呢,这是一个比较重要的知识点,所以它的知识覆盖面很广泛:但是呢,我将会对碰到的问题进行一些分析解刨(主要是为了帮助自己理清思维):也希望能够从中发现 ...

  3. Asp.NET Core2.0 项目实战入门视频课程_完整版

    END OR START? 看到这个标题,你开不开心,激不激动呢? 没错,.net core的入门课程已经完毕了.52ABP.School项目从11月19日,第一章视频的试录制,到今天完整版出炉,离不 ...

  4. 【ELK】4.spring boot 2.X集成ES spring-data-ES 进行CRUD操作 完整版+kibana管理ES的index操作

    spring boot 2.X集成ES 进行CRUD操作  完整版 内容包括: ============================================================ ...

  5. Djanjo 的app 模板路径 静态文件 完整版登录 新手三件套 以及orm

    一: django中app的概念: 一个项目可以包含多个应用(app,类似于模块,主页打开多个模块就是多个app) 创建了app,要在配置文件中注册 二:模板路径配置: 1 templates文件夹 ...

  6. kubernetes---CentOS7安装kubernetes1.11.2图文完整版

    转载请注明出处:kubernetes-CentOS7安装kubernetes1.11.2图文完整版 架构规划 k8s至少需要一个master和一个node才能组成一个可用集群. 本章我们搭建一个mas ...

  7. .netcore consul实现服务注册与发现-集群完整版

    原文:.netcore consul实现服务注册与发现-集群完整版 一.Consul的集群介绍    Consul Agent有两种运行模式:Server和Client.这里的Server和Clien ...

  8. Thinkphp5.0 仿百度糯米 开发多商家 电商平台(完整版)

    目录第1章 课程简介第2章 需求分析第3章 快速掌握thinkphp5第4章 任性的TP5模块第5章 生活服务分类管理模块第6章 百度地图应用封装第7章 打造属于TP5自己的发送邮件服务第8章 商户模 ...

  9. 探索ORACLE之ASM概念(完整版)

    探索ORACLE之ASM概念(完整版) 本文出自https://www.jb51.net/article/43527.htm ASM是Oracle 10g R2中为了简化Oracle数据库的管理而推出 ...

随机推荐

  1. celery概述

    celery介绍 Celery是一个功能完备即插即用的任务队列.它使得我们不需要考虑复杂的问题,使用非常简单.celery看起来似乎很庞大,本章节我们先对其进行简单的了解,然后再去学习其他一些高级特性 ...

  2. luogu4365 秘密袭击 (生成函数+线段树合并+拉格朗日插值)

    求所有可能联通块的第k大值的和,考虑枚举这个值: $ans=\sum\limits_{i=1}^{W}{i\sum\limits_{S}{[i是第K大]}}$ 设cnt[i]为连通块中值>=i的 ...

  3. [NOI2017]游戏

    题目描述 http://www.lydsy.com/JudgeOnline/upload/Noi2017D2.pdf 题解 如果说没有x的话,那么每一局只能有两种选择,可以描述为是/非,每条限制也可以 ...

  4. "大概能给你的磕盐增加一点幸福感✈"-[那些年的矫情]

    #--------------------------------------------------------------------------------------------------- ...

  5. kubernetes调度pod运行于master节点上

    应用背景: 使用kubeadm部署的kubernetes集群,其master节点默认拒绝将pod调度运行于其上的,加点官方的术语就是:master默认被赋予了一个或者多个“污点(taints)”,“污 ...

  6. Nginx location 匹配规则详解

    语法规则 location [=|~|~*|^~] /uri/ { … } 模式 含义 location = /uri = 表示精确匹配,只有完全匹配上才能生效 location ^~ /uri ^~ ...

  7. Tomcat系列(6)——Tomcat处理一个HTTP请求的过程

    Tomcat的架构图   图三:Tomcat Server处理一个HTTP请求的过程 处理HTTP请求过程 假设来自客户的请求为:http://localhost:8080/test/index.js ...

  8. 人工智能初识(百度ai)

    目前的人工智能做了什么? 语音识别:小米的小爱同学,苹果的siri,微软的Cortana语音合成:小米的小爱同学,苹果的siri,微软的Cortana图像识别:交通摄像头拍违章,刷脸解锁手机等视频识别 ...

  9. SQL 耗时优化

    Ø  简介 在平常的开发中,我们经常会编写各种各样的 SQL 语句,比如:SQL 查询.存储过程.或者视图查询等.当我们编写的 SQL 语句比较复杂,或者表的数据量比较大,导致查询超时!这时,就要去分 ...

  10. 《11招玩转网络安全》之第五招:DVWA命令注入

    首先还是将DVWA的安全级别设置为Low,然后单击DVWA页面左侧的Command Injection按钮. ​ 图5-1  Low级别的命令注入 这个就是最典型的命令注入接口.在文本框中输入一个IP ...