文档章节

HttpClient的使用

A__17
 A__17
发布于 2017/08/21 23:10
字数 1109
阅读 16
收藏 0
点赞 0
评论 0

HttpClient的使用:

1)httpClient的简单使用:

import java.net.URI;
import java.util.ArrayList;
import java.util.List;

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.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

public class HttpClientDemo {

	public static void main(String[] args) throws Exception {

		// 1.创建Httpclient对象
		CloseableHttpClient httpclient = HttpClients.createDefault();

		// 2.1创建http GET请求,并设置参数
		String url = "http://www.jxn.com/";
		URI uri = new URIBuilder(url).setParameter("name", "jack").setParameter("age", "1").build();
		HttpGet httpGet = new HttpGet(uri);

		// 2.2创建http POST请求,并设置参数
		HttpPost httpPost = new HttpPost(url);
		List<NameValuePair> parameters = new ArrayList<NameValuePair>();
		parameters.add(new BasicNameValuePair("name", "jack"));
		parameters.add(new BasicNameValuePair("age", "1"));
		UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(parameters);
		httpPost.setEntity(formEntity);
				
		// 3.构建请求配置信息
		RequestConfig config = RequestConfig.custom().setConnectTimeout(1000) // 创建连接的最长时间
				.setConnectionRequestTimeout(500) // 从连接池中获取到连接的最长时间
				.setSocketTimeout(10 * 1000) // 数据传输的最长时间
				.setStaleConnectionCheckEnabled(true) // 提交请求前测试连接是否可用
				.build();
		httpGet.setConfig(config);
		httpPost.setConfig(config);

		CloseableHttpResponse response = null;
		try {
			// 4.执行请求
			response = httpclient.execute(httpGet);
//            response = httpclient.execute(httpPost);
						
			if (response.getStatusLine().getStatusCode() == 200) { // 判断返回状态是否为200
				String content = EntityUtils.toString(response.getEntity(), "UTF-8");
				System.out.println(content);
			}	
		} finally {
			if (response != null) {
				response.close();
			}
			httpclient.close();
		}
	}
}

2)使用httpClient连接池:

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.HttpClientConnectionManager;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;

public class HttpClientConnectionManagerDemo {

	public static void main(String[] args) throws Exception {
		PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
		connectionManager.setMaxTotal(200); 			// 设置最大连接数
		connectionManager.setDefaultMaxPerRoute(20); 	// 设置每个主机地址的并发数

		// 执行一次get请求
		doGet(connectionManager);
	}

	public static void doGet(HttpClientConnectionManager connectionManager) throws Exception {
		CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(connectionManager).build();

		String url = "http://www.jxn.com/";
		HttpGet httpGet = new HttpGet(url);

		CloseableHttpResponse response = null;
		try {
			response = httpClient.execute(httpGet);
			if (response.getStatusLine().getStatusCode() == 200) {
				String content = EntityUtils.toString(response.getEntity(), "UTF-8");
				System.out.println(content);
			}
		} finally {
			if (response != null) {
				response.close();
			}
			// 此处不能关闭httpClient!如果把httpClient关闭掉,则连接池也会被销毁
			// httpClient.close();
		}
	}
}

3)HttpClient与Spring整合:

【1】pom.xml文件:

<dependency>
	<groupId>org.apache.httpcomponents</groupId>
	<artifactId>httpclient</artifactId>
	<version>4.3.5</version>
</dependency>

【2】spirng配置文件applicationContext-httpclient.xml:

<!-- 定义httpClient连接管理器 -->
<bean id="httpClientConnectionManager"
	class="org.apache.http.impl.conn.PoolingHttpClientConnectionManager">
	<property name="maxTotal" value="${http.maxTotal}" />
	<property name="defaultMaxPerRoute" value="${http.defaultMaxPerRoute}" />
</bean>

<!-- httpclient的构建器 -->
<bean id="httpClientBuilder" class="org.apache.http.impl.client.HttpClientBuilder">
	<property name="connectionManager" ref="httpClientConnectionManager" />
</bean>

<!-- 定义Httpclient对象。注意:该对象是多例的! -->
<bean class="org.apache.http.impl.client.CloseableHttpClient"
	factory-bean="httpClientBuilder" factory-method="build" scope="prototype">
</bean>

<!-- 请求参数的构建器 -->
<bean id="requestConfigBuilder" class="org.apache.http.client.config.RequestConfig.Builder">
	<!-- 创建连接的最长时间 -->
	<property name="connectTimeout" value="${http.connectTimeout}" />
	<!-- 从连接池中获取到连接的最长时间 -->
	<property name="connectionRequestTimeout" value="${http.connectionRequestTimeout}" />
	<!-- 数据传输的最长时间 -->
	<property name="socketTimeout" value="${http.socketTimeout}" />
	<!-- 提交请求前测试连接是否可用 -->
	<property name="staleConnectionCheckEnabled" value="${http.staleConnectionCheckEnabled}" />
</bean>

<!-- 定义请求参数对象 -->
<bean class="org.apache.http.client.config.RequestConfig" factory-bean="requestConfigBuilder" factory-method="build" />

<!-- 定期关闭无效的连接 -->
<bean class="com.jxn.common.httpclient.IdleConnectionEvictor">
	<constructor-arg index="0" ref="httpClientConnectionManager" />
</bean>

属性配置文件httpclient.properties:
	http.maxTotal=200
	http.defaultMaxPerRoute=50
	http.connectTimeout=1000
	http.connectionRequestTimeout=500
	http.socketTimeout=10000
	http.staleConnectionCheckEnabled=true

【3】封装成Service:

import java.io.IOException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
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.ContentType;
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.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.jxn.common.httpclient.HttpResult;

[@Service](https://my.oschina.net/service)
public class ApiService implements BeanFactoryAware {

	private BeanFactory beanFactory;

	@Autowired(required = false)
	private RequestConfig requestConfig;
	
	
	[@Override](https://my.oschina.net/u/1162528)
	public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
		this.beanFactory = beanFactory;
	}

	private CloseableHttpClient getHttpClient() {
		return this.beanFactory.getBean(CloseableHttpClient.class);
	}
	
	// 执行GET请求
	public String doGet(String url) throws ClientProtocolException, IOException {

		HttpGet httpGet = new HttpGet(url);
		httpGet.setConfig(requestConfig);
		CloseableHttpResponse response = null;
		try {
			// 执行请求
			response = getHttpClient().execute(httpGet);
			// 判断返回状态是否为200
			if (response.getStatusLine().getStatusCode() == 200) {
				return EntityUtils.toString(response.getEntity(), "UTF-8");
			}
		} finally {
			if (response != null) {
				response.close();
			}
		}
		return null;
	}

	// 带有参数的GET请求
	public String doGet(String url, Map<String, String> params) throws ClientProtocolException, IOException,
			URISyntaxException {
		URIBuilder builder = new URIBuilder(url);
		for (Map.Entry<String, String> entry : params.entrySet()) {
			builder.setParameter(entry.getKey(), entry.getValue());
		}
		return doGet(builder.build().toString());
	}

	// 执行post请求
	public HttpResult doPost(String url, Map<String, String> params) throws IOException {
		// 创建http POST请求
		HttpPost httpPost = new HttpPost(url);
		httpPost.setConfig(requestConfig);
		if (null != params) {
			List<NameValuePair> parameters = new ArrayList<NameValuePair>(0);
			for (Map.Entry<String, String> entry : params.entrySet()) {
				parameters.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
			}
			// 构造一个form表单式的实体
			UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(parameters, "UTF-8");
			httpPost.setEntity(formEntity);
		}

		CloseableHttpResponse response = null;
		try {
			response = getHttpClient().execute(httpPost);
			return new HttpResult(response.getStatusLine().getStatusCode(), EntityUtils.toString(
					response.getEntity(), "UTF-8"));
		} finally {
			if (response != null) {
				response.close();
			}
		}
	}

	// 执行post请求,发送json数据
	public HttpResult doPostJson(String url, String json) throws IOException {
		// 创建http POST请求
		HttpPost httpPost = new HttpPost(url);
		httpPost.setConfig(requestConfig);
		if (null != json) {
			// 构造一个字符串的实体
			StringEntity stringEntity = new StringEntity(json, ContentType.APPLICATION_JSON);
			httpPost.setEntity(stringEntity);
		}

		CloseableHttpResponse response = null;
		try {
			response = getHttpClient().execute(httpPost);
			return new HttpResult(response.getStatusLine().getStatusCode(), EntityUtils.toString(
					response.getEntity(), "UTF-8"));
		} finally {
			if (response != null) {
				response.close();
			}
		}
	}
}

// 返回的结果
public class HttpResult {

	private Integer code;
	private String data;

	public HttpResult() {
	}
	public HttpResult(Integer code, String data) {
		this.code = code;
		this.data = data;
	}
	public Integer getCode() {
		return code;
	}
	public void setCode(Integer code) {
		this.code = code;
	}
	public String getData() {
		return data;
	}
	public void setData(String data) {
		this.data = data;
	}
}

【4】实现定期关闭无效的连接:

import org.apache.http.conn.HttpClientConnectionManager;

public class IdleConnectionEvictor extends Thread {

	private final HttpClientConnectionManager connectionManager;

	private volatile boolean shutdown;

	// 创建IdleConnectionEvictor对象的时候,启动线程
	public IdleConnectionEvictor(HttpClientConnectionManager connectionManager) {
		this.connectionManager = connectionManager;
		this.start();
	}

	[@Override](https://my.oschina.net/u/1162528)
	public void run() {
		try {
			while (!shutdown) {
				synchronized (this) {
					wait(5000);
					// 关闭失效的连接(每隔5秒检查一次)
					connectionManager.closeExpiredConnections();
				}
			}
		} catch (InterruptedException ex) {
			// 结束
		}
	}

	public void shutdown() {
		shutdown = true;
		synchronized (this) {
			notifyAll();
		}
	}
}

© 著作权归作者所有

共有 人打赏支持
A__17
粉丝 2
博文 90
码字总数 101691
作品 0
朝阳
聊聊spring cloud gateway的NettyConfiguration

序 本文主要研究下spring cloud gateway的NettyConfiguration NettyConfiguration spring cloud gateway使用的是reactor的httpclient,其通过nettyClientOptions这个bean来进行构造options,......

go4it ⋅ 06/03 ⋅ 0

关于HttpClient重试策略的研究

原文出处:kingszelda 一、背景 由于工作上的业务本人经常与第三方系统交互,所以经常会使用HttpClient与第三方进行通信。对于交易类的接口,订单状态是至关重要的。 这就牵扯到一系列问题:...

kingszelda ⋅ 04/25 ⋅ 0

使用httpClient 调起https url接口

遇到的问题* 1、ssl证书信任,解决方式信任所有证书 2、生成请求体调用httpPost.setEntity()时输出的参数格式有误,有多种Entity可以选择(常用 StringEntity、UrlEncodedFormEntity、FileE...

梦魂清风 ⋅ 05/10 ⋅ 0

大家都用什么工具发起http请求的呢?

我以前喜欢用apache的 httpClient ,公司用jersey。听经理说jersey的性能好,是真的吗?我在网上并没有搜到相关的性能比较,java9也带了一个httpClient,不知性能对比起来又如何?...

暗中观察 ⋅ 04/22 ⋅ 0

聊聊spring cloud的PreserveHostHeaderGatewayFilter

序 本文主要研究下spring cloud gateway的PreserveHostHeaderGatewayFilter GatewayAutoConfiguration spring-cloud-gateway-core-2.0.0.RC2-sources.jar!/org/springframework/cloud/gatew......

go4it ⋅ 06/14 ⋅ 0

聊聊spring cloud gateway的streaming-media-types属性

序 本文主要研究下spring cloud gateway的streaming-media-types属性 配置 配置说明 GatewayProperties spring-cloud-gateway-core-2.0.0.RC2-sources.jar!/org/springframework/cloud/gatew......

go4it ⋅ 06/07 ⋅ 0

Httpclient报Timeout waiting for connection from pool 异常

下面这段代码在定时一分钟的任务里面执行: public String remoteJsonUTF8(String url) { HttpGet get = null; CloseableHttpResponse response = null; String json = null; CloseableHttpCl......

小小的小小snake ⋅ 05/17 ⋅ 0

聊聊spring cloud gateway的RemoveHopByHopHeadersFilter

序 本文主要研究一下spring cloud gateway的RemoveHopByHopHeadersFilter GatewayAutoConfiguration spring-cloud-gateway-core-2.0.0.RC1-sources.jar!/org/springframework/cloud/gateway......

go4it ⋅ 05/30 ⋅ 0

用httpclient监控网站系统运行

java httpclient做一个监控网站运行情况的程序,第一次接触,望大牛指导

消褪少年 ⋅ 05/16 ⋅ 0

Blazor 0.2.0 发布 ,将 .NET 带回到浏览器

Blazor 0.2.0 发布了 ,这是一个 Web UI 框架,可通过 WebAssembly 在任意浏览器中运行 .Net 。 Blazor 旨在简化快速的单页面 .Net 浏览器应用的构建过程,它虽然使用了诸如 CSS 和 HTML 之类...

周其 ⋅ 04/18 ⋅ 0

没有更多内容

加载失败,请刷新页面

加载更多

下一页

1.01-StringUtils的使用

import org.apache.commons.lang.StringUtils; 一、StringUtils 常用的方法: 1. 判断某一字符串是否为空 , 为空的标准是 str==null 或 str.length()==0 StringUtils.isEmpty(null) ==>tr......

静以修身2025 ⋅ 19分钟前 ⋅ 0

几道Spring 面试题

1、BeanFactory 接口和 ApplicationContext 接口有什么区别? ApplicationContext 接口继承BeanFactory接口 Spring核心工厂是BeanFactory BeanFactory采取延迟加载,第一次getBean时才会初始...

职业搬砖20年 ⋅ 21分钟前 ⋅ 0

包饺子

http://storage.slide.news.sina.com.cn/slidenews/77_ori/2018_24/74766_826131_625489.gif

霜叶情 ⋅ 22分钟前 ⋅ 0

兑吧:从自建HBase迁移到阿里云HBase实战经验

摘要: 业务介绍 兑吧集团包含兑吧网络和推啊网络,兑吧网络是一家致力于帮助互联网企业提升运营效率的用户运营服务平台,提供积分商城和媒体运营服务。推啊网络是一家互动式广告平台,经过多...

猫耳m ⋅ 33分钟前 ⋅ 0

xml解析

方法一: String s_xml1 = "<xml>" + "<head>lalalalal</head>" + "<body>1234</body>" + "</xml>"; try { DocumentBuilderFactory documentBuilderFactory......

GithubXD ⋅ 34分钟前 ⋅ 0

reuse stream

Although Java streams were designed to be operated only once, programmers still ask how to reuse a stream. From a simple web search, we can find many posts with this same issue ......

idoz ⋅ 34分钟前 ⋅ 0

兑吧:从自建HBase迁移到阿里云HBase实战经验

摘要: 业务介绍 兑吧集团包含兑吧网络和推啊网络,兑吧网络是一家致力于帮助互联网企业提升运营效率的用户运营服务平台,提供积分商城和媒体运营服务。推啊网络是一家互动式广告平台,经过多...

阿里云云栖社区 ⋅ 37分钟前 ⋅ 0

从世界杯看国内运动体育社交新能量

2018年世界杯已正式拉开帷幕,一场全世界球迷的狂欢也正式开始。 世界杯影响力:30亿+球迷的狂欢+社交话题 世界杯这个超级IP和对社交网络的引爆让更多的人目光聚焦到国内运动体育社交这个层...

ThinkSNS账号 ⋅ 37分钟前 ⋅ 0

不固定值替换

<?php$arr = 20;$data = str_replace(array(10,20,30,40),array("blue","red","green","yellow"),$arr);print_r($data);...

nsns ⋅ 39分钟前 ⋅ 0

Job for nginx.service failed 错误解决方案

今天刚在centos7上安装了nginx-1.2.11,/etc/init.d/nginx start启动时,出现 Job for nginx.service failed because the control process exited with error code. See "systemctl status n......

河图再现 ⋅ 40分钟前 ⋅ 0

没有更多内容

加载失败,请刷新页面

加载更多

下一页

返回顶部
顶部