分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 前端开发

httpclient的封装完整版

发布时间:2023-09-06 02:29责任编辑:苏小强关键词:http

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=500#5000http.request.connectTimeout=5000#数据传输的最长时间http.request.socketTimeout=30000#提交请求前测试连接是否可用http.request.staleConnectionCheckEnabled=true#设置连接总数http.pool.maxTotal=200#设置每个地址的并发数http.pool.defaultMaxPerRoute=100

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;@Servicepublic 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的封装完整版

原文地址:https://www.cnblogs.com/xQlover/p/10247660.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved