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数据库的管理而推出 ...
随机推荐
- Windows安装MongoDB 4.0并赋予用户访问权限
第一部分 Windows安装MongoDB-4.0 第一步:下载MongoDB:https://www.mongodb.com/download-center?jmp=nav#community 我目 ...
- [转载] .NET 中可以有类似 JVM 的幻像引用吗?
近日发现一篇不错的文章,文中列举了一些 GC 场景,探讨了 在 .NET 中是需要实现像 JVM 的中的幻像引用.有人质疑其不切实际,也有像 Ayende 大神一言不合就自己做了个 demo. Do ...
- django xadmin(1)
filter_horizontal 从‘多选框’的形式改变为‘过滤器’的方式,水平排列过滤器,必须是一个 ManyToManyField类型,且不能用于 ForeignKey字段,默认地,管理工具使用 ...
- <TCP/IP原理> (二) OSI模型和TCP/IP协议族
1.OSI参考模型 1)作用 2)各层的名称和功能 2.对分层网络协议体系的理解 1)不同节点:层次组成不同,作用不同 2)横向理解:虚通信.对等实体.协议.PDU 3)纵向理解:封装与解封.服务.接 ...
- CF350E 【Wrong Floyd】
Description 给定n个点,m条边,k个标记点,hack掉给出的程序. Solution 先考虑不可能hack掉的情况.当所有点都是标记点的时候肯定不能hack掉,也就是\(n=k\).还有就 ...
- Java程序设计第一次作业
虽说这学期Java比上学期的C语言要简单些许,但是初次面对java程序,还是有点难度的.
- 【Network】优化问题——Label Smoothing
滴:转载引用请注明哦[握爪]https://www.cnblogs.com/zyrb/p/9699168.html 今天来进行讨论深度学习中的一种优化方法Label smoothing Regular ...
- 什么是Annotation
Annotation 被称为注解,在Java开发中是相当常见的,通过注解,我们可以简化代码提高开发效率.例如Override Annotation,这个应该算是在开发过程中使用最多的注解了.注解(An ...
- 老男孩Python全栈学习 S9 日常作业 010
1.写函数,接收n个数字,求这些参数数字的和. def func1(*Num): num = 0 for i in Num: num += i return num 2.读代码,回答:代码中,打印出来 ...
- DirectX11--HR宏关于dxerr库的替代方案
DirectX11 With Windows SDK完整目录 欢迎加入QQ群: 727623616 可以一起探讨DX11,以及有什么问题也可以在这里汇报. 综述 参考文章:https://blogs. ...