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内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • springboot 如何解决cross跨域请求的问题

    springboot 如何解决cross跨域请求的问题

    这篇文章主要介绍了springboot 如何解决cross跨域请求的问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-10-10
  • Java 线程池全面总结与详解

    Java 线程池全面总结与详解

    在一个应用程序中,我们需要多次使用线程,也就意味着,我们需要多次创建并销毁线程。而创建并销毁线程的过程势必会消耗内存。而在Java中,内存资源是及其宝贵的,所以,我们就提出了线程池的概念
    2021-10-10
  • Spring Boot两种配置文件properties和yml区别

    Spring Boot两种配置文件properties和yml区别

    这篇文章主要为大家介绍了java面试中常见问到的Spring Boot两种配置文件properties和yml区别解答,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-07-07
  • Spring Boot开发RESTful接口与http协议状态表述

    Spring Boot开发RESTful接口与http协议状态表述

    这篇文章主要为大家介绍了Spring Boot开发RESTful接口与http协议状态表述,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步
    2022-03-03
  • synchronized底层实现原理

    synchronized底层实现原理

    这篇文章主要介绍了synchronized底层实现原理,想弄懂它的实现synchronized的原理,我们只能通过看编译好的字节码文件,下面文章的详细内容,我们就先从测试类开始吧,需要的小伙伴可以参考一下
    2022-01-01
  • SpringBoot读取自定义配置文件方式(properties,yaml)

    SpringBoot读取自定义配置文件方式(properties,yaml)

    这篇文章主要介绍了SpringBoot读取自定义配置文件方式(properties,yaml),具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-07-07
  • Mybatis MapperScannerConfigurer自动扫描Mapper接口生成代理注入到Spring的方法

    Mybatis MapperScannerConfigurer自动扫描Mapper接口生成代理注入到Spring的方法

    这篇文章主要给大家介绍了关于Mybatis MapperScannerConfigurer自动扫描将Mapper接口生成代理注入到Spring的相关资料,文中通过示例代码介绍的非常详细,需要的朋友可以参考下
    2019-03-03
  • Spring Security之LogoutSuccessHandler注销成功操作方式

    Spring Security之LogoutSuccessHandler注销成功操作方式

    这篇文章主要介绍了Spring Security之LogoutSuccessHandler注销成功操作方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2024-08-08
  • 排序算法图解之Java归并排序的实现

    排序算法图解之Java归并排序的实现

    归并排序是建立在归并操作上的一种有效,稳定的排序算法,该算法是采用分治法(Divide and Conquer)的一个非常典型的应用。本文主要介绍了归并排序的实现,需要的可以参考一下
    2022-11-11
  • 聊聊在Servlet中怎么上传文件

    聊聊在Servlet中怎么上传文件

    很多朋友不清楚在Servlet中怎么上传文件,谈到这个问题,首先需要我们掌握开发servlet的步骤,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧
    2021-05-05

最新评论