SpringBoot 使用RestTemplate实现调用服务

本文详细介绍如何在SpringBoot项目中使用RestTemplate进行远程HTTP调用。包括依赖配置、RestTemplate实例化及设置超时时间,同时展示了如何通过POST和GET方式调用远程API,并附带了实际的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

SpringBoot的搭建可以看一下我之前写的一篇博客

IDEA 搭建SpringBoot项目_大锅睿的博客-CSDN博客

准备工作

要使用RestTemplate需要引入依赖,web依赖也可以在创建项目时选择Web -> Web

<!-- web -->
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-web</artifactId>
</dependency>

<!-- 远程调用 httpclient -->
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.5</version>
</dependency>

 注入RestTemplate

  可以直接在Application中配置一个RestTemplate Bean

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

@SpringBootApplication
public class RemoteApplication {
    @Bean 
    public RestTemplate restTemplate() {
        HttpComponentsClientHttpRequestFactory httpRequestFactory = new HttpComponentsClientHttpRequestFactory();
        httpRequestFactory.setConnectionRequestTimeout(30 * 1000);
        httpRequestFactory.setConnectTimeout(30 * 3000);
        httpRequestFactory.setReadTimeout(30 * 3000);
        return new RestTemplate(httpRequestFactory);
    }
    public static void main(String[] args) {
        SpringApplication.run(RemoteApplication.class, args);
    }
}

也可以编写一个RestTemplate配置类

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

/**
 * @Description RestTemplate配置
 * @Author CWR
 * @Date 2022/7/14 16:37
 */
@Configuration
public class RestTemplateConfig {
    @Bean
    public RestTemplate restTemplate() {
        HttpComponentsClientHttpRequestFactory httpRequestFactory = new HttpComponentsClientHttpRequestFactory();
        httpRequestFactory.setConnectionRequestTimeout(30 * 1000);
        httpRequestFactory.setConnectTimeout(30 * 3000);
        httpRequestFactory.setReadTimeout(30 * 3000);
        return new RestTemplate(httpRequestFactory);
    }
}

  实体类

import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;

@Data
public class UserEntity {
    @JsonProperty("user_id")
    private Long userId;
    private String name;
    private String phone;
}
import lombok.Data;

@Data
public class Result {
    private Integer code;
    private String message;
}

  controller

import com.cwr.remote.model.db.UserEntity;
import com.cwr.remote.model.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;


@RequestMapping("/remote")
//允许跨域访问
@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
public class RemoteController {
    //自动注入RestTemplate 
    private final RestTemplate restTemplate;

    @Autowired
    public RemoteController(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    /**
     * 调用远程服务添加用户信息
     *
     * @param userEntity 用户实体
     * @return
     */
    @PostMapping("/add-user")
    public Result addUser(@RequestBody UserEntity userEntity) {
        HttpEntity<UserEntity> entity = new HttpEntity<>(userEntity);
        ResponseEntity<Result> resultResponseEntity = this.restTemplate.exchange(
                "http://xxx.xxx.xxx.xxx/user/add",
                HttpMethod.POST, entity, Result.class);
        if (resultResponseEntity.getStatusCode() == HttpStatus.OK) {
            return resultResponseEntity.getBody();
        }
        return null;
    }

    /**
     * 调用远程服务查询单个用户信息
     *
     * @param id 用户id
     * @return
     */
    @GetMapping("/find-user-id/{id}")
    public UserEntity findOne(@PathVariable Long id) {
        ResponseEntity<UserEntity> resultResponseEntity = this.restTemplate.exchange(
                String.format("http://xxx.xxx.xxx.xxx/user/find-id/%s", id),
                HttpMethod.GET, null, UserEntity.class);
        if (resultResponseEntity.getStatusCode() == HttpStatus.OK) {
            return resultResponseEntity.getBody();
        }
        return null;
    }
}

这里详细讲一下exchange( )方法

public <T> ResponseEntity<T> exchange(String url, 
                                      HttpMethod method, 
                                      @Nullable HttpEntity<?> requestEntity,
                                      Class<T> responseType) 
  • url:请求地址,如果需要在url中带参数,使用String.format(),用%s拼接即可;
  •  method:请求方式,HttpMethod是一个枚举类型,有GET、POST、DELETE等方法;
  •  requestEntity:请求参数,这个主要是POST等有请求体的方法才需要,GET、DELETE等方法可以为null;
  •  responseType:返回数据类型。

测试结果(我使用的是Postman)

   

### 使用 RestTemplate 发送 HTTP 请求 在 Spring Boot 应用程序中,`RestTemplate` 是一个同步客户端,用于执行 HTTP 请求。为了使用 `RestTemplate` 进行 HTTP 请求,应用程序需要配置并注入该模板。 #### 配置 RestTemplate 实例 创建 `RestTemplate` 对象可以通过定义它作为一个 Bean 来完成,这样可以利用 Spring 的自动管理功能来处理其生命周期[^3]: ```java @Configuration public class AppConfig { @Bean public RestTemplate restTemplate() { return new RestTemplate(); } } ``` 一旦有了这个 Bean 定义,在任何组件里都可以通过依赖注入的方式获取到 `RestTemplate` 实例。 #### 执行 GET 请求 下面是一个简单的例子,展示了如何使用 `RestTemplate` 向指定 URL 发出 GET 请求,并接收字符串类型的响应体内容[^4]: ```java @RestController @RequestMapping("/api") public class MyController { private final RestTemplate restTemplate; @Autowired public MyController(RestTemplateBuilder restTemplateBuilder) { this.restTemplate = restTemplateBuilder.build(); } @GetMapping("/callExternalService") public ResponseEntity<String> callExternalService() { String url = "http://localhost:8802/testRestGet?username=zhangsan"; String response = restTemplate.getForObject(url, String.class); if (response != null) { return ResponseEntity.ok(response); } else { return ResponseEntity.notFound().build(); } } } ``` 这段代码片段说明了如何构建带有查询参数的 URL 并调用外部服务接口;如果成功接收到数据,则返回给前端用户;如果没有找到资源则返回 404 错误码。 #### 设置自定义请求头 有时可能还需要向服务器传递额外的信息作为请求的一部分,比如身份验证令牌或其他元数据。这可以通过设置请求头的方式来实现。这里展示了一个添加用户代理信息的例子: ```java @Test public void testCustomHeaders(){ HttpHeaders headers = new HttpHeaders(); headers.add("User-Agent", "MyApp/1.0"); HttpEntity<Void> entity = new HttpEntity<>(headers); ResponseEntity<String> result = restTemplate.exchange( "http://example.com/api", HttpMethod.GET, entity, String.class ); System.out.println(result.getBody()); } ``` 此部分解释了怎样构造包含特定头部字段的消息实体,并将其应用于实际的网络通信过程中。
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值