如何在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
相关产品推荐
相关产品推荐

