Spring Boot如何使用httpcomponents实现http请求

 更新时间:2023年07月17日 10:24:08   作者:青铜爱码士  
这篇文章主要介绍了Spring Boot使用httpcomponents实现http请求的示例代码,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

基于org.apache.httpcomponents的httpclient实现,其它的实现方式都行。

1. pom文件

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>org.example</groupId>
    <artifactId>registerTest</artifactId>
    <packaging>pom</packaging>
    <version>1.0-SNAPSHOT</version>
    <modules>
        <module>server</module>
        <module>provider1</module>
    </modules>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.1.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.1.23</version>
        </dependency>
    </dependencies>
</project>

2. HttpClient实现get和post方法

package http.client;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
public class HttpClient {
    private String url;
    private String contentType;
    private String encoding;
    private JSONObject data;
    public HttpClient(String url, String encoding, String contentType, JSONObject data) {
        this.url = url;
        this.data = data;
        this.encoding = encoding == null ? "UTF-8" : encoding;
        this.contentType = contentType == null ? "application/json" : contentType;
    }
    public String httpGet() throws Exception {
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        HttpGet httpGet = new HttpGet(url);
        HttpResponse response = httpClient.execute(httpGet);
        if (response.getStatusLine().getStatusCode() != 200) {
            throw new Exception("调用服务端异常.");
        }
        HttpEntity res = response.getEntity();
        String resultData = EntityUtils.toString(res);
        System.out.println("从服务端返回结果: " + resultData);
        httpClient.close();
        return resultData;
    }
    public String httpPost() throws Exception {
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        String json = JSONObject.toJSONString(data);
        StringEntity entity = new StringEntity(json);
        entity.setContentEncoding(encoding);
        entity.setContentType(contentType);
        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(entity);
        HttpResponse response = httpClient.execute(httpPost);
        if (response.getStatusLine().getStatusCode() != 200) {
            throw new Exception("调用服务端异常.");
        }
        HttpEntity res = response.getEntity();
        String resultData = EntityUtils.toString(res);
        System.out.println("从服务端返回结果: " + resultData);
        httpClient.close();
        return resultData;
    }
}

3. 创建springboot工程,提供接口访问

package register.control;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import register.list.RegisterList;
@RestController
@RequestMapping("/register")
public class Register {
    @Autowired
    RegisterList registerList;
    @PostMapping("/register")
    public String register(@RequestBody JSONObject data) {
        //处理注册逻辑
        return registerList.add(data.getString("name"), data.getString("ip"));
    }
    @GetMapping("/list/{name}")
    public Object getList(@PathVariable(value = "name", required = true) String name) {
        //获取注册列表
        return registerList.getByName(name);
    }
    @GetMapping("/list/all")
    public Object getList() {
        return registerList.getAll();
    }
}

4. 创建springboot工程,实现http请求

通过ApplicationRunner 实现启动自动运行。

package common.register;
import com.alibaba.fastjson.JSONObject;
import http.client.HttpClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
@Component
public class Register implements ApplicationRunner {
    @Value("${model.name}")
    String name;
    @Value("${model.host}")
    String host;
    @Value("${model.port}")
    String port;
    @Value("${register.url}")
    String url;
    //发送注册消息
    @Override
    public void run(ApplicationArguments args) throws Exception {
        JSONObject data = new JSONObject() {{
            put("name", name);
            put("ip", "http://" + host + ":" + port);
        }};
        HttpClient client = new HttpClient(url, null, null, data);
        client.httpPost();
    }
}

结果:成功返回

在这里插入图片描述

到此这篇关于Spring Boot使用httpcomponents实现http请求的文章就介绍到这了,更多相关Spring Boot使用httpcomponents内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Java正则表达式处理特殊字符转义的方法

    Java正则表达式处理特殊字符转义的方法

    由于正则表达式定了一些特殊字符,而有时候需要对这些特殊字符进行匹配的话就需要进行转义了,下面这篇文章主要给大家介绍了Java正则表达式处理特殊字符转义的方法,需要的朋友可以参考借鉴,下面来一起看看吧。
    2017-01-01
  • Jdbctemplate多数据源配置方法详解

    Jdbctemplate多数据源配置方法详解

    这篇文章主要介绍了Jdbctemplate多数据源配置方法详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-06-06
  • java自定义JDBC实现连接池

    java自定义JDBC实现连接池

    本文主要介绍了java自定义JDBC实现连接池,包含实现JDBC连接池以及SQLException 异常的处理,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2024-02-02
  • MyBatis 核心配置文件及映射文件详解

    MyBatis 核心配置文件及映射文件详解

    MyBatis是支持定制化SQL、存储过程以及高级映射的优秀的持久层框架,本文重点介绍MyBatis 核心配置文件及映射文件,需要的朋友可以参考下
    2023-01-01
  • java使用正则抓取网页邮箱

    java使用正则抓取网页邮箱

    这篇文章主要为大家详细介绍了java使用正则抓取网页邮箱的相关资料,感兴趣的小伙伴们可以参考一下
    2016-05-05
  • Spark Maven项目打包后找不到主类问题及解决

    Spark Maven项目打包后找不到主类问题及解决

    在使用IDEA、Maven创建Spark项目时,遇到打包后Scala程序找不到主类的问题,原因是Maven缺少scala-maven-plugin插件,通过添加该插件并重新构建项目,问题得到解决
    2026-02-02
  • Java8中Stream使用的一个注意事项

    Java8中Stream使用的一个注意事项

    最近在工作中发现了对于集合操作转换的神器,java8新特性 stream,但在使用中遇到了一个非常重要的注意点,所以这篇文章主要给大家介绍了关于Java8中Stream使用过程中的一个注意事项,需要的朋友可以参考借鉴,下面随着小编来一起学习学习吧。
    2017-11-11
  • SpringMvc+Angularjs 实现多文件批量上传

    SpringMvc+Angularjs 实现多文件批量上传

    本文通过实例代码给大家讲解了SpringMvc+Angularjs 实现多文件批量上传功能,非常不错,具有参考借鉴价值,需要的朋友一起学习吧
    2017-03-03
  • SpringBoot2.x使用POI实现导入数据到Excel

    SpringBoot2.x使用POI实现导入数据到Excel

    这篇文章主要为大家详细介绍了SpringBoot2.x如何使用POI实现导入数据到Excel,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下
    2025-07-07
  • Java代理的几种实现方式总结

    Java代理的几种实现方式总结

    本文将通过例子说明java代理的几种实现方式,并比较它们之间的差异,文中通过代码示例给大家介绍的非常详细,对大家的学习或工作有一定的参考价值,需要的朋友可以参考下
    2023-12-12

最新评论