RestTemplate.exchange正常但FeignClient调用第三方API报400错误原因
问题原因及解决方案
核心原因
两种请求的Content-Type格式不匹配:
- RestTemplate代码使用
MultiValueMap作为请求体,默认会以application/x-www-form-urlencoded(表单)格式发送请求,完全符合第三方接口的接收要求,因此请求成功。 - FeignClient代码中使用
@RequestBody注解,会将NameMatchRequestDto对象序列化为application/json格式的请求体发送,但第三方接口仅支持表单格式的请求,因此返回400 Bad Request错误。
修正方案
调整FeignClient的写法,让它以表单格式发送请求,有两种常用方式:
方式一:逐个指定请求参数
import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; public interface NameMatchClient { @PostMapping( value = "/v1/name/match", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE ) ResponseEntity<NameMatchResponseDto> matchNames( @RequestParam("pan_name") String panName, @RequestParam("pan_name_combined") String panNameCombined, @RequestParam("bank_name") String bankName ); }
方式二:使用MultiValueMap传递表单参数
import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.util.MultiValueMap; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; public interface NameMatchClient { @PostMapping( value = "/v1/name/match", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE ) ResponseEntity<NameMatchResponseDto> matchNames( @RequestBody MultiValueMap<String, String> formData ); }
内容的提问来源于stack exchange,提问作者ujjawal raghuvanshi
相关产品推荐
相关产品推荐

