httpclient的封装完整版
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的封装完整版的更多相关文章
- C# .NET更智能的数据库操作的封装完整版(重构)
前述: 第一次发表文章,不过是对数据库简单的封装,主要是阐述下思路.那么在上篇文章,在大家的指导下和提出意见,并自己对代码进行了思考.在这两天我重构了新的框架,我觉得我写的可以称得上框架,为什么?请大 ...
- rip路由协议 细节分析及实例配置【完整版】
rip路由协议 细节分析及实例配置[完整版] RIP呢,这是一个比较重要的知识点,所以它的知识覆盖面很广泛:但是呢,我将会对碰到的问题进行一些分析解刨(主要是为了帮助自己理清思维):也希望能够从中发现 ...
- Asp.NET Core2.0 项目实战入门视频课程_完整版
END OR START? 看到这个标题,你开不开心,激不激动呢? 没错,.net core的入门课程已经完毕了.52ABP.School项目从11月19日,第一章视频的试录制,到今天完整版出炉,离不 ...
- 【ELK】4.spring boot 2.X集成ES spring-data-ES 进行CRUD操作 完整版+kibana管理ES的index操作
spring boot 2.X集成ES 进行CRUD操作 完整版 内容包括: ============================================================ ...
- Djanjo 的app 模板路径 静态文件 完整版登录 新手三件套 以及orm
一: django中app的概念: 一个项目可以包含多个应用(app,类似于模块,主页打开多个模块就是多个app) 创建了app,要在配置文件中注册 二:模板路径配置: 1 templates文件夹 ...
- kubernetes---CentOS7安装kubernetes1.11.2图文完整版
转载请注明出处:kubernetes-CentOS7安装kubernetes1.11.2图文完整版 架构规划 k8s至少需要一个master和一个node才能组成一个可用集群. 本章我们搭建一个mas ...
- .netcore consul实现服务注册与发现-集群完整版
原文:.netcore consul实现服务注册与发现-集群完整版 一.Consul的集群介绍 Consul Agent有两种运行模式:Server和Client.这里的Server和Clien ...
- Thinkphp5.0 仿百度糯米 开发多商家 电商平台(完整版)
目录第1章 课程简介第2章 需求分析第3章 快速掌握thinkphp5第4章 任性的TP5模块第5章 生活服务分类管理模块第6章 百度地图应用封装第7章 打造属于TP5自己的发送邮件服务第8章 商户模 ...
- 探索ORACLE之ASM概念(完整版)
探索ORACLE之ASM概念(完整版) 本文出自https://www.jb51.net/article/43527.htm ASM是Oracle 10g R2中为了简化Oracle数据库的管理而推出 ...
随机推荐
- CentOS 7 安装Git
服务器端 1.先从yum安装git yum –y install git 2.在需要的位置创建一个裸仓库(最后以.git结尾) cd /usr/local mkdir git cd git git i ...
- POJ1988 Cube stacking(非递归)
n有N(N<=30,000)堆方块,开始每堆都是一个方块.方块编号1 – N. 有两种操作: nM x y : 表示把方块x所在的堆,拿起来叠放到y所在的堆上. nC x : 问方块x下面有多少 ...
- [SDOI2017]遗忘的集合
[SDOI2017]遗忘的集合 综合了很多套路的题 一看就是完全背包 生成函数! 转化为连乘积形式 Pi....=F 求Ln! 降次才可以解方程 发现方程是: f[i]=∑t|i : bool(t)* ...
- Mac新手入门使用教程 - Finder 技巧
1,了解MAC电脑桌面. Finder:中间DOCK栏下最左边蓝白相间的图标. DOCK栏:包括Finder.前往应用程序.创建所有应用程序的快捷方式(google浏览器等).系统偏好设置.堆栈. ...
- CountDownLatch、CyclicBarrier、Semaphore共同之处与区别以及各自使用场景
区别 CountDownLatch 使一个线程A或是组线程A等待其它线程执行完毕后,一个线程A或是组线程A才继续执行.CyclicBarrier:一组线程使用await()指定barrier,所有线程 ...
- IE7下使用兼容Icon-Font CSS类
Iconfont在IE7下需要使用unicode方式,但是这种方式不太方便,使用以下代码可使IE7像普通用法使用. @font-face {font-family: "anticon&quo ...
- RabbitMQ installation
以windows环境测试 Erlang http://www.erlang.org/downloads 下载并安装 运行时软件 Erlang OTP 21.3 Windows 64-bit Binar ...
- [C++] const与指针的关系
首先快速复习一些基础. 考虑下面的声明兼定义式: int p = 10; p的基础数据类型是int. 考虑下面的声明兼定义式: const int a = 10; a的基础数据类型是int,a是一个常 ...
- java接口多实现和多继承
package test; interface mouth { public abstract void speak(); } interface nose{ public abstract void ...
- Java装箱的 " == " 的问题
装箱和拆箱 packagecom.xzj.Test; /* * @ author thisxzj * @ create 2019-02-25 10:56 */ publicclassBase{ ...