用spring发送http请求

目录

1. 使用 RestTemplate:

2、使用 WebClient:


 我的其他博客

HTTP与HTTTPS的区别-CSDN博客

什么情况下会产生StackOverflowError(栈溢出)和OutOfMemoryError(堆溢出)怎么排查-CSDN博客

谈谈我对HashMap扩容机制的理解及底层实现-CSDN博客

Redis 两种持久化方式 AOF 和 RDB-CSDN博客MySQL中的锁(简单)-CSDN博客

JDK、JRE、JVM的特点和关联-CSDN博客

面向对象的三大特征-CSDN博客

二分查找(Java) 详细讲解 一文足矣-CSDN博客

在Spring中,你可以使用RestTemplateWebClient来发送HTTP请求。下面分别给出使用这两个类的简单示例。

现在pom.xml中导入依赖

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>2.6.0</version> <!-- Specify the version of Spring Boot -->
</dependency>
<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-webflux</artifactId>
            <version>2.6.0</version> <!-- Specify the version of Spring Boot -->
</dependency>

1. 使用 RestTemplate:

import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

public class HttpRequestExample {

    public static void main(String[] args) {
        // 创建 RestTemplate 实例
        RestTemplate restTemplate = new RestTemplate();

        // 设置请求 URL
        String url = "https://api.example.com/data";

        // 发送 GET 请求,并获取响应
        ResponseEntity<String> responseEntity = restTemplate.getForEntity(url, String.class);

        // 获取响应体
        String responseBody = responseEntity.getBody();

        // 处理响应
        System.out.println("Response: " + responseBody);
    }
}

2、使用 WebClient:

import org.springframework.web.reactive.function.client.WebClient;

public class HttpRequestExample {

    public static void main(String[] args) {
        // 创建 WebClient 实例
        WebClient webClient = WebClient.create();

        // 设置请求 URL
        String url = "https://api.example.com/data";

        // 发送 GET 请求,并获取响应
        String responseBody = webClient.get()
                .uri(url)
                .retrieve()
                .bodyToMono(String.class)
                .block();

        // 处理响应
        System.out.println("Response: " + responseBody);
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

还在路上的秃头

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值