spring集成httpclient配置的详细过程

一、简介

HttpClient是Apache Jakarta Common下的子项目,用来提供高效的、最新的、功能丰富的支持HTTP协议的客户端编程工具包,并且它支持HTTP协议最新的版本和建议。HttpClient已经应用在很多的项目中,比如Apache Jakarta上很著名的另外两个开源项目Cactus和HTMLUnit都使用了HttpClient。

下载地址: http://hc.apache.org/downloads.cgi

二、特性

1. 基于标准、纯净的java语言。实现了Http1.0和Http1.1

2. 以可扩展的面向对象的结构实现了Http全部的方法(GET, POST, PUT, DELETE, HEAD, OPTIONS, and TRACE)。

3. 支持HTTPS协议。

4. 通过Http代理建立透明的连接。

5. 利用CONNECT方法通过Http代理建立隧道的https连接。

6. Basic, Digest, NTLMv1, NTLMv2, NTLM2 Session, SNPNEGO/Kerberos认证方案。

7. 插件式的自定义认证方案。

8. 便携可靠的套接字工厂使它更容易的使用第三方解决方案。

9. 连接管理器支持多线程应用。支持设置最大连接数,同时支持设置每个主机的最大连接数,发现并关闭过期的连接。

10. 自动处理Set-Cookie中的Cookie。

11. 插件式的自定义Cookie策略。

12. Request的输出流可以避免流中内容直接缓冲到socket服务器。

13. Response的输入流可以有效的从socket服务器直接读取相应内容。

14. 在http1.0和http1.1中利用KeepAlive保持持久连接。

15. 直接获取服务器发送的response code和 headers。

16. 设置连接超时的能力。

17. 实验性的支持http1.1 response caching。

18. 源代码基于Apache License 可免费获取。

spring httpclient

HTTP 协议可能是现在 Internet 上使用得最多、最重要的协议了,越来越多的 Java 应用程序需要直接通过 HTTP 协议来访问网络资源。虽然在 JDK 的 java.net 包中已经提供了访问 HTTP 协议的基本功能,但是对于大部分应用程序来说,JDK 库本身提供的功能还不够丰富和灵活。HttpClient 是 Apache Jakarta Common 下的子项目,用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议。

spring与httpclient集成方式如下:

引入jar包

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

2.编写执行get和post请求的java类

package com.wee.common.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.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.wee.common.bean.HttpResult;

@Service
public class HttpClientService {

    @Autowired
    private CloseableHttpClient httpClient;
    @Autowired
    private RequestConfig requestConfig;

    /**
     * 执行GET请求
     *
     * @param url
     * @return
     * @throws IOException
     * @throws ClientProtocolException
     */
    public String doGet(String url) throws ClientProtocolException, IOException {
        // 创建http GET请求
        HttpGet httpGet = new HttpGet(url);
        httpGet.setConfig(this.requestConfig);

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

    /**
     * 带有参数的GET请求
     *
     * @param url
     * @param params
     * @return
     * @throws URISyntaxException
     * @throws IOException
     * @throws ClientProtocolException
     */
    public String doGet(String url, Map<String, String> params)
            throws ClientProtocolException, IOException, URISyntaxException {
        URIBuilder uriBuilder = new URIBuilder(url);
        for (String key : params.keySet()) {
            uriBuilder.addParameter(key, params.get(key));
        }
        return this.doGet(uriBuilder.build().toString());
    }

    /**
     * 执行POST请求
     *
     * @param url
     * @param params
     * @return
     * @throws IOException
     */
    public HttpResult doPost(String url, Map<String, String> params) throws IOException {
        // 创建http POST请求
        HttpPost httpPost = new HttpPost(url);
        httpPost.setConfig(this.requestConfig);
        if (params != null) {
            // 设置2个post参数,一个是scope、一个是q
            List<NameValuePair> parameters = new ArrayList<NameValuePair>();
            for (String key : params.keySet()) {
                parameters.add(new BasicNameValuePair(key, params.get(key)));
            }
            // 构造一个form表单式的实体
            UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(parameters, "UTF-8");
            // 将请求实体设置到httpPost对象中
            httpPost.setEntity(formEntity);
        }

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

    /**
     * 执行POST请求
     *
     * @param url
     * @return
     * @throws IOException
     */
    public HttpResult doPost(String url) throws IOException {
        return this.doPost(url, null);
    }

    /**
     * 提交json数据
     *
     * @param url
     * @param json
     * @return
     * @throws ClientProtocolException
     * @throws IOException
     */
    public HttpResult doPostJson(String url, String json) throws ClientProtocolException, IOException {
        // 创建http POST请求
        HttpPost httpPost = new HttpPost(url);
        httpPost.setConfig(this.requestConfig);

        if (json != null) {
            // 构造一个form表单式的实体
            StringEntity stringEntity = new StringEntity(json, ContentType.APPLICATION_JSON);
            // 将请求实体设置到httpPost对象中
            httpPost.setEntity(stringEntity);
        }

        CloseableHttpResponse response = null;
        try {
            // 执行请求
            response = this.httpClient.execute(httpPost);
            return new HttpResult(response.getStatusLine().getStatusCode(),
                    EntityUtils.toString(response.getEntity(), "UTF-8"));
        } finally {
            if (response != null) {
                response.close();
            }
        }
    }

}
 HttpResult.java

public class HttpResult {

    /**
     * 状态码
     */
    private Integer status;
    /**
     * 返回数据
     */
    private String data;

    public HttpResult() {
    }

    public HttpResult(Integer status, String data) {
        this.status = status;
        this.data = data;
    }

    public Integer getStatus() {
        return status;
    }

    public void setStatus(Integer status) {
        this.status = status;
    }

    public String getData() {
        return data;
    }

    public void setData(String data) {
        this.data = data;
    }

}

3.spring和httpClient整合配置文件

<!-- 定义连接管理器 -->
    <bean id="httpClientConnectionManager"
        class="org.apache.http.impl.conn.PoolingHttpClientConnectionManager"
        destroy-method="close">
        <!-- 最大连接数 -->
        <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 id="httpClient" class="org.apache.http.impl.client.CloseableHttpClient"
        factory-bean="httpClientBuilder" factory-method="build" scope="prototype">
    </bean>

    <!-- 定义清理无效连接 -->
    <bean class="com.taotao.common.httpclient.IdleConnectionEvictor"
        destroy-method="shutdown">
        <constructor-arg index="0" ref="httpClientConnectionManager" />
    </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 id="requestConfig" class="org.apache.http.client.config.RequestConfig" factory-bean="requestConfigBuilder" factory-method="build">
    </bean>

4.httpclient.properties

httpClient.maxTotal=200
httpClient.defaultMaxPerRoute=50
httpClient.connectTimeout=1000
httpClient.connectionRequestTimeout=500
httpClient.socketTimeout=10000
httpClient.staleConnectionCheckEnabled=true

5.使用一个单独的线程完成连接池中的无效链接的清理

package com.wee.common.httpclient;

import org.apache.http.conn.HttpClientConnectionManager;

public class IdleConnectionEvictor extends Thread {

    private final HttpClientConnectionManager connMgr;

    private volatile boolean shutdown;

    public IdleConnectionEvictor(HttpClientConnectionManager connMgr) {
        this.connMgr = connMgr;
        // 启动当前线程
        this.start();
    }

    @Override
    public void run() {
        try {
            while (!shutdown) {
                synchronized (this) {
                    wait(5000);
                    // 关闭失效的连接
                    connMgr.closeExpiredConnections();
                }
            }
        } catch (InterruptedException ex) {
            // 结束
        }
    }

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

到此这篇关于spring集成httpclient配置的文章就介绍到这了,更多相关spring httpclient配置内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • spring boot openfeign从此和httpClient说再见详析

    前言 在微服务设计里,服务之间的调用是很正常的,通常我们使用httpClient来实现对远程资源的调用,而这种方法需要知识服务的地址,业务接口地址等,而且需要等他开发完成后你才可以去调用它,这对于集成开发来说,不是什么好事 ,产生了A业务与B业务的强依赖性,那么我们如何进行解耦呢,答案就是openfeign框架,它与是springcloudy里的一部分. 1 添加包引用 'org.springframework.cloud:spring-cloud-starter-openfeign', 注意:

  • springboot整合httpClient代码实例

    这篇文章主要介绍了springboot整合httpClient代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 创建httpClientConfig配置类 @Configuration @PropertySource(value="classpath:/properties/httpClient.properties") public class HttpClientConfig { @Value("${http.ma

  • spring boot封装HttpClient的示例代码

    最近使用到了HttpClient,看了一下官方文档:HttpClient implementations are expected to be thread safe. It is recommended that the same instance of this class is reused for multiple request executions,翻译过来的意思就是:HttpClient的实现是线程安全的,可以重用相同的实例来执行多次请求.遇到这种描述的话,我们就应该想到,需要对H

  • Spring中@Scheduled和HttpClient的连环坑

    前言 本文主要给大家介绍了关于Spring中@Scheduled和HttpClient的坑,分享出来供大家参考学习,下面话不多说了,来一起看看详细的介绍吧. 曾经踩过一个大坑: 由于业务特殊性,会定时跑很多定时任务,对业务数据进行补偿操作等. 在Spring使用过程中,我们可以使用@Scheduled注解可以方便的实现定时任务. 有一天早上突然发现,从前一天晚上某一时刻开始,所有的定时任务全部都卡死不再运行了. @Scheduled默认单线程 经排查后发现,我们使用@Scheduled注解默认的

  • Spring远程调用HttpClient/RestTemplate的方法

    一.HttpClient 两个系统间如何互相访问?两个tomcat上的项目如何互相访问? 采用HttpClient实现跨系统的接口调用. 介绍: 官网:http://hc.apache.org/index.html 现在也叫:HttpComponents HttpClient可以发送get.post.put.delete....等请求 使用: 导入坐标 <dependency> <groupId>org.apache.httpcomponents</groupId> &

  • Spring+Http请求+HttpClient实现传参

    一.HttpClient简介 HTTP 协议可能是现在 Internet 上使用得最多.最重要的协议了,越来越多的 Java 应用程序需要直接通过 HTTP 协议来访问网络资源.虽然在 JDK 的 java net包中已经提供了访问 HTTP 协议的基本功能,但是对于大部分应用程序来说,JDK 库本身提供的功能还不够丰富和灵活.HttpClient 是 Apache Jakarta Common 下的子项目,用来提供高效的.最新的.功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 H

  • 关于springboot 中使用httpclient或RestTemplate做MultipartFile文件跨服务传输的问题

    大家好,因为近期做需求中遇到了文件上传这个东西,而且我这个还是跨服务去传输文件的所以我这边使用了httpclient和RestTemplate去做,但是最后还是用的httpclient.feign和RestTemplate在超大文件下会OOM所以适用于小文件传输我这边测试的在1G以下.httpclient好像是无限哈哈哈.(具体多少大家有时间可以去测一下) 1.被调用服务的Controller 1.这块使用@RequestParam("file")或者@RequestPart(&quo

  • spring集成httpclient配置的详细过程

    一.简介 HttpClient是Apache Jakarta Common下的子项目,用来提供高效的.最新的.功能丰富的支持HTTP协议的客户端编程工具包,并且它支持HTTP协议最新的版本和建议.HttpClient已经应用在很多的项目中,比如Apache Jakarta上很著名的另外两个开源项目Cactus和HTMLUnit都使用了HttpClient. 下载地址: http://hc.apache.org/downloads.cgi 二.特性 1. 基于标准.纯净的java语言.实现了Htt

  • C++中opencv4.1.0环境配置的详细过程

    准备 Open CV 的文件 : https://opencv.org/releases/ 解压到哪里无所谓,我们后面会把需要的文件复制到 Solution 的目录里面.我本机解压到F:\opencv4.1.0 新建Open CV 的测试工程: 新建一空白的C++工程,设为opencv_test 工程设置为Debug的x64模式 右键单击工程->属性,打开配置的属性页 在VC++目录中添加包含目录: F:\opencv4.1.0\build\include;F:\opencv4.1.0\buil

  • spring框架集成flyway项目的详细过程

    什么是Spring Spring是一个开源框架,它由Rod Johnson创建.它是为了解决企业应用开发的复杂性而创建的. Spring使用基本的JavaBean来完成以前只可能由EJB完成的事情.   然而,Spring的用途不仅限于服务器端的开发.从简单性.可测试性和松耦合的角度而言,任何Java应用都可以从Spring中受益.    目的:解决企业应用开发的复杂性    功能:使用基本的JavaBean代替EJB,并提供了更多的企业应用功能    范围:任何Java应用    它是一个容器

  • Spring集成JPA配置懒加载报错解决方案

    一:报错no session 因为entitymanager对象在事物提交后就关闭了 报错的 no session相当于sql的session 解决办法:解决办法 在web.xmL配置一个过滤器 使其在这个session中的manager在结束后再关闭open <!--配置openmanager--> <filter> <filter-name>openEntity</filter-name> <filter-class>org.springfr

  • 教你开发脚手架集成Spring Boot Actuator监控的详细过程

    目录 集成 引入依赖 配置文件 访问验证 端点 Endpoints Health Info 安全 高级 自定义健康检查 自定义metrics指标 PID PORT过程监控 自定义管理端点路径 自定义管理服务器端口 暴露数据给Prometheus 集成 引入依赖 在项目的pom.xml中增加以下依赖 <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-

  • nginx安装以及配置的详细过程记录

    目录 1 nginx 介绍 1 什么是nginx 2 应用场景 2 nginx安装 1 下载 2 安装要求的环境 1.需要安装gcc环境 2.第三方的开发包 3 nginx安装过程 3 启动nginx 4 查看nginx是否启动 5 关闭nginx 6 重启nginx 7 刷新配置文件 8 关闭防火墙,开启远程访问 9 访问nginx 10 配置虚拟主机 11 通过端口区分不同的主机 12 多个域名区分虚拟主机 1 什么是域名 2 nginx配置 3 测试 13 正向代理 14 反向代理 15

  • openGauss数据库JDBC环境连接配置的详细过程(Eclipse)

    目录 1.测试环境 2.准备 2.1 PC端安装配置JDK11 2.2下载JDBC驱动并解压 3 进行eclipse配置 1.测试环境 客户端系统:Windows 10 客户端软件:eclipse 2020-09 Server操作系统:openEuler 20.03 64bit with ARM 数据库版本:openGauss 2.0.0 2.准备 2.1 PC端安装配置JDK11 DOS窗口输入“java -version”,查看JDK版本,确认为JDK11版本.如果未安装JDK,请 从官方网

  • Spring集成Mybatis过程详细讲解

    目录 为啥学习集成Mybatis ORM框架 实现步骤 为啥学习集成Mybatis ORM框架 虽然Spring中提供了JDBCTemplate模块,已经很大程度了解决了JDBC代码的复杂度,但它仍然是和Java代码写在一起的.反观 Mybatis 将 Sql 语句写在配置文件中,使得SQL语句和程序实现了松耦合.而且提供了些许标签,使得SQL可以是动态的.在ORM基础上想要更好的用Spring的DI.AOP.事务处理.Junit支持等实现成果,学会使用 Spring 框架集成 Mybatis

  • java spring整合junit操作(有详细的分析过程)

    此博客解决了什么问题: 解决测试的时候代码冗余的问题,解决了测试工程师的编码能力可能没有开发工程师编码能力的问题,解决了junit单元测试和spring注解相结合! 测试类代码:(只给大家展示测试类的代码) public class AccountServiceTest { @Test public void testFindAll(){ //1.获取容器 ApplicationContext ac=new ClassPathXmlApplicationContext("bean.xml&quo

  • SpringBoot项目集成Flyway详细过程

    一.Flyway Flyway是独立于数据库的应用.管理并跟踪数据库变更的数据库版本管理工具.用通俗的话讲,Flyway可以像Git管理不同人的代码那样,管理不同人的sql脚本,从而做到数据库同步. 二.流程 1. 首先配置好flyway的基本信息后,运行项目,会在数据库表中默认新建一个数据表用于存储flyway的运行信息,默认的数据库名:flyway_schema_history 2. 紧接着Flyway将开始扫描文件系统或应用程序的类路径进行迁移.然后,Flyway的数据迁移将基于对用sql

随机推荐