掌握Spring 中的 RestTemplate

添加依赖项

如果你使用Maven,需要在pom.xml文件中包含Spring Web依赖项来使用RestTemplate:

xml 复制代码
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

如果使用的是Gradle,在build.gradle文件中添加以下依赖项:

arduino 复制代码
implementation 'org.springframework.boot:spring-boot-starter-web'

创建RestTemplate Bean

在Spring配置类中定义一个RestTemplate bean,以便在需要的地方注入它:

java 复制代码
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

@Configuration
public class AppConfig {

    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }
}

使用RestTemplate进行HTTP请求

GET请求

要执行GET请求,可以使用getForObjectgetForEntity方法。

java 复制代码
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
public class RestTemplateService {

    @Autowired
    private RestTemplate restTemplate;

    public String getPost(int id) {
        String url = "https://jsonplaceholder.typicode.com/posts/" + id;
        return restTemplate.getForObject(url, String.class);
    }
}

POST请求

对于POST请求,可以使用postForObjectpostForEntity方法。

java 复制代码
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import java.util.HashMap;
import java.util.Map;

@Service
public class RestTemplateService {

    @Autowired
    private RestTemplate restTemplate;

    public String createPost() {
        String url = "https://jsonplaceholder.typicode.com/posts";
        Map<String, String> request = new HashMap<>();
        request.put("title", "foo");
        request.put("body", "bar");
        request.put("userId", "1");
        return restTemplate.postForObject(url, request, String.class);
    }
}

PUT请求

要更新资源,可以使用put方法:

java 复制代码
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import java.util.HashMap;
import java.util.Map;

@Service
public class RestTemplateService {

    @Autowired
    private RestTemplate restTemplate;

    public void updatePost(int id) {
        String url = "https://jsonplaceholder.typicode.com/posts/" + id;
        Map<String, String> request = new HashMap<>();
        request.put("title", "updated title");
        request.put("body", "updated body");
        restTemplate.put(url, request);
    }
}

DELETE请求

要删除资源,使用delete方法:

java 复制代码
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
public class RestTemplateService {

    @Autowired
    private RestTemplate restTemplate;

    public void deletePost(int id) {
        String url = "https://jsonplaceholder.typicode.com/posts/" + id;
        restTemplate.delete(url);
    }
}

处理响应

RestTemplate提供了几种处理响应的方法。最简单的是getForObject,它直接返回响应体。或者,getForEntity返回一个ResponseEntity,其中包含更多详细信息,如响应头和状态码。

java 复制代码
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
public class RestTemplateService {

    @Autowired
    private RestTemplate restTemplate;

    public ResponseEntity<String> getPostEntity(int id) {
        String url = "https://jsonplaceholder.typicode.com/posts/" + id;
        return restTemplate.getForEntity(url, String.class);
    }
}

自定义RestTemplate

超时配置

可以为RestTemplate使用的底层HTTP客户端配置超时:

java 复制代码
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

@Configuration
public class AppConfig {

    @Bean
    public RestTemplate restTemplate() {
        HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
        factory.setReadTimeout(5000);
        factory.setConnectTimeout(5000);
        return new RestTemplate(factory);
    }
}

拦截器

可以添加拦截器来操作请求和响应:

java 复制代码
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.web.client.RestTemplate;
import java.io.IOException;
import java.util.Collections;

@Configuration
public class AppConfig {

    @Bean
    public RestTemplate restTemplate() {
        RestTemplate restTemplate = new RestTemplate();
        restTemplate.setInterceptors(Collections.singletonList(new CustomClientHttpRequestInterceptor()));
        return restTemplate;
    }
}

class CustomClientHttpRequestInterceptor implements ClientHttpRequestInterceptor {

    @Override
    public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
        // 在此处修改请求
        ClientHttpResponse response = execution.execute(request, body);
        // 在此处修改响应
        return response;
    }
}

注意事项

  • 阻塞特性:RestTemplate是同步的,会阻塞执行线程,直到请求完成。对于高吞吐量或对延迟敏感的应用程序,这可能是一个缺点。

  • 弃用:随着WebClient的引入,RestTemplate不再是新开发的首选。Spring团队建议在非阻塞和响应式应用程序中使用WebClient。

  • 缺乏高级功能:RestTemplate缺乏WebClient提供的一些高级功能和灵活性,例如更好的非阻塞I/O处理和响应式流处理。

结论

RestTemplate是在Spring应用程序中与RESTful Web服务交互的强大且易于使用的工具。其简单的API允许快速集成和处理HTTP请求和响应。

相关推荐
S***26751 小时前
基于SpringBoot和Leaflet的行政区划地图掩膜效果实战
java·spring boot·后端
马剑威(威哥爱编程)1 小时前
鸿蒙6开发视频播放器的屏幕方向适配问题
java·音视频·harmonyos
JIngJaneIL1 小时前
社区互助|社区交易|基于springboot+vue的社区互助交易系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·论文·毕设·社区互助
V***u4532 小时前
MS SQL Server partition by 函数实战二 编排考场人员
java·服务器·开发语言
这是程序猿2 小时前
基于java的ssm框架旅游在线平台
java·开发语言·spring boot·spring·旅游·旅游在线平台
i***t9193 小时前
基于SpringBoot和PostGIS的云南与缅甸的千里边境线实战
java·spring boot·spring
k***08293 小时前
【监控】spring actuator源码速读
java·spring boot·spring
麦麦鸡腿堡3 小时前
Java_网络编程_InetAddress类与Socket类
java·服务器·网络
@大迁世界3 小时前
相信我兄弟:Cloudflare Rust 的 .unwrap() 方法在 330 多个数据中心引发了恐慌
开发语言·后端·rust
vx_dmxq2113 小时前
【PHP考研互助系统】(免费领源码+演示录像)|可做计算机毕设Java、Python、PHP、小程序APP、C#、爬虫大数据、单片机、文案
java·spring boot·mysql·考研·微信小程序·小程序·php