错误代码如下:
@FeignClient(value="{}",configuration=FeignClientLogConfiguration.class, contextId="id")
public interface FeignClient{
@PostMapping(value="/test", headers={"Content-Type=application/json;charset=gbk"})
String test(String req);
}
方法调用如下:
@Autowired
FeignClient feignClient;
public void getTest(请求实体类 req){
String jsonReq = JSON.toJSONString(req);
String resp = feignClient.test(jsonReq);
log.info("响应报文:{}", resp);// 日志打印出来中文乱码
}
在网上寻找各种调用方法测试,如 自定义Hystrix熔断策略,自定义编码拦截等,效果都不理想;
最后通过更改返回的响应对象,实现了中文乱码转换正常,代码如下:
import feign.Response;
@FeignClient(value="{}",configuration=FeignClientLogConfiguration.class, contextId="id")
public interface FeignClient{
@PostMapping(value="/test", headers={"Content-Type=application/json;charset=gbk"})
Response test(String req);
}
方法调用如下:
@Autowired
FeignClient feignClient;
public void getTest(请求实体类 req){
String jsonReq = JSON.toJSONString(req);
Response resp = feignClient.test(jsonReq);
String resp = this.printToRespInfo(resp);
log.info("响应报文:{}", resp);// 日志打印出来中文乱码
}
/**
* 格式化提取响应数据
*/
private String printToRespInfo(Response response){
InputStream inputStream = null;
try{
Response.Body body = response.body();
inputStream = body.asInputStream();
return IOUtils.toString(inputStream, "GBK");
} catch (IOException e){
log.error("response to json is error");
} finally {
IOUtils.closeQuietly(inputStream);
}
return null;
}
希望本次分享会对大家有所帮助!