You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Retrofit POST请求中同时传递请求体与请求参数token?

Retrofit同时传递请求体与查询参数的正确方式

问题场景

后端Spring Boot接口定义如下,需要接收POST请求的请求体(AppointmentBookingDto)和URL查询参数(token):

@PostMapping("appointment/book")
public ResponseEntity<ApiResponse> bookAppointment(@RequestBody AppointmentBookingDto appointmentBookingDto, @RequestParam("token") String token) throws DataNotFoundException, ParseException, DataAlreadyExistException {
  return appointmentBookingService.bookAppointment(appointmentBookingDto, token);
}

但Android端Retrofit接口错误使用@Path传递token,导致参数无法被后端正确接收:

@POST("appointment/book")
Call<ApiResponse> bookAppointment(@Body AppointmentBookingDto appointmentBookingDto, @Path("token") String token); 

解决方案

将Retrofit接口中的@Path("token")替换为@Query("token"),因为后端用@RequestParam接收的是URL查询参数(格式为?token=xxx),而@Path用于绑定路径变量(如appointment/book/{token}),两者不匹配。

修正后的Retrofit接口代码:

@POST("appointment/book")
Call<ApiResponse> bookAppointment(@Body AppointmentBookingDto appointmentBookingDto, @Query("token") String token); 

说明

  • @Body对应后端的@RequestBody,负责传递JSON格式的请求体数据,无需修改。
  • @Query("token")会自动将token拼接为URL的查询参数,符合后端@RequestParam("token")的接收要求。
  • 原调用代码无需修改,保持现有参数传递逻辑即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 06:35:37