Httpclient与spring整合

本文详细介绍如何在Spring Boot项目中配置并使用HttpClient进行高效网络请求,包括连接管理、请求参数设置及跨域请求处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

添加相应依赖

配置

在applicationContext.xml中添加

<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-4.0.xsd
	http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">

	<!-- 创建连接管理器 -->
	<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.clc.web.httpclient.IdleConnectionEvictor">
		<constructor-arg index="0" ref="httpClientConnectionManager" />
	</bean>

</beans>

HttpClient实现跨域请求的service

package com.taotao.web.service;

import java.io.IOException;
import java.net.URI;
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.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.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.clc.web.bean.Result;//自建的包装类,包含状态码和响应数据

@Service
public class HttpClientService {
	@Autowired
	private RequestConfig config;
	@Autowired
	private CloseableHttpClient httpClient;

	/**
	 * 无参的get请求
	 * 
	 * @param url
	 * @return
	 */
	public String doGet(String url) {
		// HttpGet对象
		HttpGet get = new HttpGet(url);
		get.setConfig(config);
		CloseableHttpResponse response = null;
		try {
			response = httpClient.execute(get);
			if (response != null && response.getStatusLine().getStatusCode() == 200) {
				return EntityUtils.toString(response.getEntity(), "utf-8");
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (response != null) {
				try {
					response.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			//httpClient.close();
			//连接池会随着httpClientde的销毁而销毁,所以此处不能关闭httpClient
		}
		return null;
	}

	/**
	 * 有参的get请求
	 * 
	 * @param url
	 * @return
	 */
	public String doGet(String url, Map<String, Object> params) {
		List<NameValuePair> nvprs = new ArrayList<>();
		// 遍历map
		for (String key : params.keySet()) {
			NameValuePair nvpr = new BasicNameValuePair(key, params.get(key).toString());
			nvprs.add(nvpr);
		}
		CloseableHttpResponse response = null;
		try {
			URI uri = new URIBuilder(url).addParameters(nvprs).build();
			// HttpGet对象
			HttpGet get = new HttpGet(uri);
			get.setConfig(config);
			response = httpClient.execute(get);
			if (response != null && response.getStatusLine().getStatusCode() == 200) {
				return EntityUtils.toString(response.getEntity(), "utf-8");
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (response != null) {
				try {
					response.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return null;
	}

	// Save Update Delete (状态不同 返回值不一样? 有的有返回值 有的没有返回值。)
	public Result doPost(String url, Map<String, Object> params) {
		List<NameValuePair> nvprs = new ArrayList<>();
		// 遍历map
		for (String key : params.keySet()) {
			NameValuePair nvpr = new BasicNameValuePair(key, params.get(key).toString());
			nvprs.add(nvpr);
		}
		CloseableHttpResponse response = null;
		try {
			URI uri = new URIBuilder(url).addParameters(nvprs).build();
			// HttpGet对象
			HttpPost post = new HttpPost(uri);
			post.setConfig(config);
			response = httpClient.execute(post);
			return new Result(response.getStatusLine().getStatusCode(),
					EntityUtils.toString(response.getEntity(), "utf-8"));
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (response != null) {
				try {
					response.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return null;
	}

	// Save Update Delete (状态不同 返回值不一样? 有的有返回值 有的没有返回值。)
	public Result doPost(String url) {
		CloseableHttpResponse response = null;
		try {
			// HttpGet对象
			HttpPost post = new HttpPost(url);
			post.setConfig(config);
			response = httpClient.execute(post);
			return new Result(response.getStatusLine().getStatusCode(),
					EntityUtils.toString(response.getEntity(), "utf-8"));
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (response != null) {
				try {
					response.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return null;
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值