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数据库的管理而推出 ...
随机推荐
- Get Remote Computer Install Software
#requires -Version 2 function Get-Software { param ( [string] $DisplayName='*', [string] $UninstallS ...
- SolidWorks装配体
- fast-ai lesson1 错误处理(CNN创建)
报错信息: name 'ConvLearner' is not defined 在最新的fast ai包中,ConvLearner已经被create_cnn取代,所以替换为下列语句就好了: learn ...
- DataReader转Dictionary数据类型之妙用
datareader转dictionary有很多用处,可以输出表中部分字段转实体字段,以前需要全部字段输出或者再建一个实体模型才行,这样就可以减少数据库的输出量了,特别是某些接口的格式化输出很方便. ...
- Cucumber启动类配置
@CucumberOptions ( features = "src/test/resources", glue = {"Steps"}, tags = {&q ...
- C#编程中的Image/Bitmap与base64的转换及 Base-64 字符数组或字符串的长度无效问题 解决
最近用base64编码传图片遇到了点问题,总结下. 首先总结下base64编码的逻辑,来自网络:https://www.cnblogs.com/zhangchengye/p/5432276.html ...
- Python模拟弹道轨迹
http://www.itongji.cn/cms/article/articledetails?articleid=5029 最近美国把萨德系统部署到韩国,一时心血来潮就用python模拟最简单的弹 ...
- docker 删除镜像
有时候我们不需要某个镜像,需要对它进行删除.1.停止所有的container,这样才能够删除其中的images: docker stop $(docker ps -a -q) 如果想要删除所有cont ...
- python之路(10)类的内置函数
目录 isinstance()和issubclass() __setitem__.__getitem__和__delitem__ __str__和__reper__ __format__ __slot ...
- 使用Docker安装SonarQube
需先安装docker和docker-compose.见:https://www.cnblogs.com/hackyo/p/9280042.html 在任意目录下新建文件docker-compose.y ...