feign调用第三方接口,编码定义GBK,响应中文乱码处理方式
作者:耨耨菲
这篇文章主要介绍了feign调用第三方接口,编码定义GBK,响应中文乱码处理方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
feign调用第三方接口,编码定义GBK,响应中文乱码
错误代码
如下:
@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;
}总结
好了,以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
