You need to enable JavaScript to run this app. Spring Boot中使用RestTemplate发起PUT请求如何直接传入DTO类作为参数
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot中使用RestTemplate发起PUT请求如何直接传入DTO类作为参数

Spring Boot RestTemplate 直接传入DTO作为PUT请求参数的实现方案

问题根因

你之前的写法存在两处错误:

  • RestTemplate.put()方法的第二个参数是请求体对象,第三个参数是URI路径占位符的对应值,你将dataDto传入第三个参数,完全没有用到参数传递的逻辑
  • 默认情况下传入put()方法的对象会被序列化为JSON放到请求体中,而你的服务端接口是从查询参数中取值,自然无法接收

解决方案

场景1:服务端接口从查询参数取值(对应你原有拼接参数的逻辑)

你可以通过ObjectMapper将DTO对象直接转为Map,再批量添加到URI的查询参数中,无需手动逐个拼接:

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

// Spring Boot自动装配了ObjectMapper,直接注入即可
@Autowired
private ObjectMapper objectMapper;

public String callRemoteService(DataDto dataDto) {
    final String uri = "http://127.0.0.1:8888/key";
    RestTemplate restTemplate = new RestTemplate();
    HttpHeaders headers = new HttpHeaders();
    headers.set(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE);

    // 将DTO转为参数Map
    Map<String, Object> paramMap = objectMapper.convertValue(dataDto, new TypeReference<Map<String, Object>>() {});

    // 批量添加查询参数
    UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(uri);
    paramMap.forEach(builder::queryParam);

    HttpEntity<?> entity = new HttpEntity<>(headers);
    ResponseEntity<String> response = restTemplate.exchange(
            builder.toUriString(),
            HttpMethod.PUT,
            entity,
            String.class
    );
    return response.getBody();
}

场景2:服务端接口支持接收JSON请求体(用@RequestBody注解接收参数)

这种场景不需要拼接查询参数,直接将DTO放到请求体中即可:

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

public String callRemoteService(DataDto dataDto) {
    final String uri = "http://127.0.0.1:8888/key";
    RestTemplate restTemplate = new RestTemplate();
    HttpHeaders headers = new HttpHeaders();
    headers.set(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE);
    headers.setContentType(MediaType.APPLICATION_JSON);

    // 将DTO放入请求实体
    HttpEntity<DataDto> requestEntity = new HttpEntity<>(dataDto, headers);
    ResponseEntity<String> response = restTemplate.exchange(
            uri,
            HttpMethod.PUT,
            requestEntity,
            String.class
    );
    return response.getBody();
}

内容的提问来源于stack exchange,提问作者Ruyut

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.19 17:36:02