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. Markdown基础语法小结

    一.前言 Markdown是一种可以使用普通文本编辑器编写的标记语言,通过简单的标记语法,它可以使普通文本内容具有一定的格式. --摘自百度百科 没想到一向不太靠谱的百度百科这次竟有了如此精辟的解释. ...

  2. VS2010查看源码对应的汇编语言

    在学习c++中const关键字的过程中,经常会看到各种寄存器.汇编指令分析,像下面的图这样 左图是g++中反汇编的效果,右图是vs中反汇编的效果. 如果我们想要查看源码所对应的汇编语言,应该怎么操作呢 ...

  3. 011 Socket定义客户端

    引入命名空间: using System.Net; using System.Net.Sockets; using System.Threading;

  4. python学习05

    数据类型之字典dict.set集合 1).字典dict 1. dict_1={'name':'tom','age':18} 是以键值对(key-value)的方式,其中键是可hash值的,即表示键是唯 ...

  5. react native 安卓home返回键页面刷新

    import { withNavigationFocus } from 'react-navigation'; class Warngreete extends React.Component { c ...

  6. JSP/Serlet 使用fileupload上传文件

    需要引用的jar commons-fileupload-1.3.1.jar commons-io-2.2.jar index.jsp <body> <center> <h ...

  7. Python面向对象之反射

    一.反射的基本概念 二.反射示例 三.反射的应用 一.反射的基本概念 反射:可以用字符串的方式去访问对象的属性,调用对象的方法(但是不能去访问方法),Python中一切皆对象,都可以使用反射. 反射有 ...

  8. Base64 加密解密

    /// <summary> /// 编码 Base64 /// </summary> /// <param name="code"></p ...

  9. APK改之理 手游修改改编安卓程序工具安装使用教程

    APK改之理 手游修改改编安卓程序工具安装使用教程 --APK破解付费程序 apk改之理是pc平台上一款非常好用的apk反编译工具,他将反编译以及签名等功能集中在一起,并且拥有非常人性化的操作界面,如 ...

  10. pyenv安装及常用命令

    1.pyenv安装 #下载安装脚本curl https://pyenv.run | bash #添加环境变量 echo 'export PATH="/root/.pyenv/bin:$PAT ...