feign调用传入HttpServletRequest request, HttpServletResponse response 报错feign.codec.EncodeException: Error converting request body
这个问题通常是因为在传递HttpServletRequest request, HttpServletResponse response时,Feign编码器无法将它们转换为请求体。
解决方案:
- 将HttpServletRequest request, HttpServletResponse response从参数中移除。
- 在Feign客户端调用时,手动设置请求头、cookie等信息来替代HttpServletRequest和HttpServletResponse。
示例代码:
FeignClient接口调用的接口,这个接口接收的是HttpServletRequest参数
@RequestMapping(value = "/getDictItems/{dictCode}", method = RequestMethod.GET)
public Result<List<DictModel>> getDictItems(@PathVariable("dictCode") String dictCode, @RequestParam(value = "sign",required = false) String sign,HttpServletRequest request) {
//业务处理
return result;
}
FeignClient接口
通过@RequestHeader注解和@CookieValue注解手动设置了请求头和cookie信息。这样就可以避免使用HttpServletRequest和HttpServletResponse传参导致的错误。
@GetMapping(value = "/sys/dict/getDictItems/{dictCode}")
Result<List<DictModel>> getDictItems(@PathVariable("dictCode") String dictCode, @RequestParam(value = "sign",
required = false) String sign, @RequestHeader("Authorization") String token,
@CookieValue("SESSIONID") String sessionId);
contronller调用FeignClient的接口
controller接收的是HttpServletRequest,但是传给FeignClient接口的是token和sessionid。
@GetMapping(value = "/getDictItems/{dictCode}")
public Result<List<DictModel>> getDictItems(@PathVariable("dictCode") String dictCode,
@RequestParam(value = "sign",required = false) String sign,
@NotNull HttpServletRequest request) {
return ddgSysClient.getDictItems(dictCode,sign,
request.getHeader("Authorization"),
request.getRequestedSessionId());
}