Java教程:SpringBoot项目如何使用RestTemplate发送与接收http/https请求

前言:

我们都知道,发送http请求在项目开发中非常常见,不管是前端向后端,还是后端服务与服务之间,大多数都是通过http请求来进行数据交互,或者https,通常包括GET、POST、PUT、DELETE等几种方法,在以往SSM等架构中,经常会使用HttpURLConnection、HttpClient、Apache HttpClient或OkHttp库来实现这一目的,使用起来较为繁琐,编写难度较高,现如今在SpringBoot项目上,可以直接使用‌RestTemplate来直接实现,大大简化了服务之间的调用,它封装了底层HTTP库,提供模板化的API支持GET、POST、PUT、DELETE等HTTP方法,适用于同步阻塞场景的Web服务交互。‌‌

在这里插入图片描述

在使用‌RestTemplate之前我们先来了解一下什么是http,以及http的核心组成。

一、什么是http

HTTP(‌超文本传输协议‌)是互联网上应用最广泛的‌应用层协议‌,用于在客户端(通常是浏览器)和服务器之间‌传输超文本(如网页)及其他资源‌(如图片、视频、文件等)。它是万维网(WWW)数据通信的基础。

二、http的核心组成

1、起始行(Start Line)

  • 请求报文‌中称为‌请求行(Request Line)‌:

     包含请求方法(如 GET、POST)、目标URI(资源路径)和协议版本(如 HTTP/1.1),格式示例:GET /index.html HTTP/1.1
    
  • 响应报文‌中称为‌状态行(Status Line)‌:

     包含协议版本、状态码(如 200、404)和状态描述(如 OK、Not Found),格式示例:HTTP/1.1 200 OK
    

2、头部(Headers)

  • 由多个键值对(如 Content-Type: text/html)组成,传递报文元信息

3、主体(Body)

  • ‌可选部分‌,用于传输实际数据(如表单提交内容、文件或服务器返回的HTML)
  • 在请求中常见于 POST、PUT 方法;在响应中存放资源内容

我们已经知道,要发送http必须包含三组数据,接下来就来讲解一下如何使用RestTemplate来发送GET/POST/PUT/DELETE请求。

三、如何使用RestTemplate发送请求

RestTemplate提供了getForObject(),postForObject()与getForEntity(),postForEntity(),exchange(),能够处理大部分请求,本次着重讲解这几个

1、首先我们需要导入依赖,请确保你的服务有Spring Web依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
Springboot提供两种实例RestTemplate方式,一种是注解依赖,另一种直接new即可
@Autowired
private RestTemplate restTemplate;
RestTemplate restTemplate = new RestTemplate();

2、 如何发送GET请求

因get请求不推荐也不允许将入参放入body体中,并且对url长度有所限制,适合简单请求发送

普通GET请求:

// 普通GET请求
String url = "https://api.example.com/data";
String result = restTemplate.getForObject(url, String.class);
System.out.println("响应内容: " + result);

携带响应头与响应状态码的get请求:

// 携带响应头与响应状态码的get请求
String url = "https://api.example.com/data";
ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);
HttpStatus statusCode = response.getStatusCode(); // 获取状态码
HttpHeaders headers = response.getHeaders();      // 获取响应头
String body = response.getBody();                 // 获取响应体
System.out.println("获取响应状态码: " + statusCode.toString());
System.out.println("获取响应头: " + headers.toString());
System.out.println("获取响应体: " + body);

携带参数的get请求:

// 携带参数的get请求
String url = "https://api.example.com/data?key1="+"我是key1的值"+"&"+"key2="+"我是key2的值";
ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);
HttpStatus statusCode = response.getStatusCode(); // 获取状态码
HttpHeaders headers = response.getHeaders();      // 获取响应头
String body = response.getBody();                 // 获取响应体
System.out.println("获取响应状态码: " + statusCode.toString());
System.out.println("获取响应头: " + headers.toString());
System.out.println("获取响应体: " + body);

携带请求头的get请求:

// 携带请求头的get请求
HttpHeaders headers = new HttpHeaders();
headers.add("Authorization", "Bearer token123"); // 添加请求头
HttpEntity<String> requestEntity = new HttpEntity<>(headers);
String url = "https://api.example.com/data?key1="+"我是key1的值"+"&"+"key2="+"我是key2的值";
ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, requestEntity, String.class);
HttpStatus statusCode = response.getStatusCode(); // 获取状态码
HttpHeaders resHeaders = response.getHeaders();      // 获取响应头
String body = response.getBody();                 // 获取响应体
System.out.println("获取响应状态码: " + statusCode.toString());
System.out.println("获取响应头: " + resHeaders.toString());
System.out.println("获取响应体: " + body);

3、 如何发送POST请求

如遇文件或大量敏感数据,或服务端有要求的,需要使用post请求方式

简单POST请求:

// 简单POST请求
String url = "https://api.example.com/data";
String result = restTemplate.postForObject(url, null, String.class);
System.out.println("响应内容: " + result);

携带响应头与响应状态码的POST请求:

// 携带响应头与响应状态码的POST请求
String url = "https://api.example.com/data";
ResponseEntity<String> response = restTemplate.postForEntity(url, null, String.class);
HttpStatus statusCode = response.getStatusCode(); // 获取状态码
HttpHeaders headers = response.getHeaders();      // 获取响应头
String body = response.getBody();                 // 获取响应体
System.out.println("获取响应状态码: " + statusCode.toString());
System.out.println("获取响应头: " + headers.toString());
System.out.println("获取响应体: " + body);

发送表单数据:

// 发送表单数据
String url = "https://api.example.com/data";
MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
params.add("username", "admin");
params.add("password", "123456");
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
HttpEntity requestEntity = new HttpEntity(params, headers);
ResponseEntity<String> response = restTemplate.postForEntity(url, requestEntity, String.class);
HttpStatus statusCode = response.getStatusCode(); // 获取状态码
HttpHeaders responseHeaders = response.getHeaders();      // 获取响应头
String body = response.getBody();                 // 获取响应体
System.out.println("获取响应状态码: " + statusCode.toString());
System.out.println("获取响应头: " + responseHeaders.toString());
System.out.println("获取响应体: " + body);

发送JSON数据:

// 发送JSON数据
String url = "https://api.example.com/data";
Map<String, Object> map = new HashMap<>();
map.put("username", "admin");
map.put("password", "123456");
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentType(MediaType.APPLICATION_JSON);
HttpEntity httpEntity = new HttpEntity(map, httpHeaders);
ResponseEntity<String> response = restTemplate.postForEntity(url, httpEntity, String.class);
HttpStatus statusCode = response.getStatusCode(); // 获取状态码
HttpHeaders responseHeaders = response.getHeaders();      // 获取响应头
String body = response.getBody();                 // 获取响应体
System.out.println("获取响应状态码: " + statusCode.toString());
System.out.println("获取响应头: " + responseHeaders.toString());
System.out.println("获取响应体: " + body);

发送文件:

// 发送文件
String url = "https://api.example.com/data";
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
Resource fileResource = new FileSystemResource("/path/to/file.txt");
MultiValueMap<String, Object> multiValueMap = new LinkedMultiValueMap<>();
multiValueMap.add("file", fileResource);
multiValueMap.add("comment", "测试文件上传");
HttpEntity httpEntity = new HttpEntity(multiValueMap, headers);
ResponseEntity<String> response = restTemplate.postForEntity(url, httpEntity, String.class);
HttpStatus statusCode = response.getStatusCode(); // 获取状态码
HttpHeaders responseHeaders = response.getHeaders();      // 获取响应头
String body = response.getBody();                 // 获取响应体
System.out.println("获取响应状态码: " + statusCode.toString());
System.out.println("获取响应头: " + responseHeaders.toString());
System.out.println("获取响应体: " + body);

4、 如何发送其他请求

其他请求在get中大家也看到,可以采用exchange方式来实现
// 类似如下
Map<String, String> requestParam = new HashMap<>();
requestParam.put("admin", "123456");
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentType(MediaType.APPLICATION_JSON);
HttpEntity requestEntity = new HttpEntity(requestParam, httpHeaders);
String url = "https://api.example.com/data";
ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.PUT, requestEntity, String.class);
HttpStatus statusCode = response.getStatusCode(); // 获取状态码
HttpHeaders resHeaders = response.getHeaders();      // 获取响应头
String body = response.getBody();                 // 获取响应体
System.out.println("获取响应状态码: " + statusCode.toString());
System.out.println("获取响应头: " + resHeaders.toString());
System.out.println("获取响应体: " + body);

我们点进HttpMethod里看一下:
在这里插入图片描述

可以看到所有的请求都可以使用exchange来实现

5、 如何发送Https请求

在发送https请求时如果服务端SSL证书有误或其他原因,会导致发送不成功无效证书的情况,解决办法也很简单,我们只需要忽略它的证书即可!

增加配置类:

import org.apache.http.conn.ssl.*;
import org.apache.http.impl.client.*;
import org.springframework.http.client.*;
import org.springframework.web.client.RestTemplate;

import javax.net.ssl.*;

public class SSLConfig {
    public static RestTemplate getUnsafeRestTemplate() throws Exception {
        SSLContext sslContext = SSLContexts.custom()
                .loadTrustMaterial(null, (chain, authType) -> true).build();

        CloseableHttpClient httpClient = HttpClients.custom()
                .setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
                .setSSLContext(sslContext)
                .build();

        return new RestTemplate(new HttpComponentsClientHttpRequestFactory(httpClient));
    }
}

然后创建实例对象:

RestTemplate restTemplate = SSLConfig.getUnsafeRestTemplate();

此时就可以正常发送https请求了。

本次教程到这里就结束了,希望大家多多关注支持(首席摸鱼师 微信同号),持续跟踪最新文章吧~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值