shell脚本保存为GBK编码文件执行curl请求时,发送的 Body为GBK编码,接收接口为SpringbootRest接口, 会出现乱码无法解析的问题。
解决方法:
方法1.Shell发送端:
转换为utf-8
sourecontent="{"a":"我是中文"}"
content=$(echo "$sourecontent" | iconv -c -f gbk -t utf-8)
curl -X POST -D content http://xxxxxx
方法2:Springboot 服务端:
添加配置,对指定的url增加 Interceptors,添加编码处理
@Configuration
public class GbkConfiguration implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new HandlerInterceptor() {
@Override
public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) {
try {
TriggerRunRequest request = null;
String bodyStr = IOUtils.toString(httpServletRequest.getInputStream(), "GBK");
// log.info("+++++++++++++++++++++++++111:{}", bodyStr);
if (StringUtils.hasText(bodyStr)) {
request = JsonUtils.parseObject(bodyStr, TriggerRunRequest.class).orElse(null);
}
httpServletRequest.setAttribute("request", request);
//httpServletRequest.
} catch (IOException e) {
throw new RuntimeException(e);
}
return true;
}
@Override
public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) {
}
@Override
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
}
}).addPathPatterns("/xxx/xxx").addPathPatterns("");
}
// @Override
// public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
// FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter();
// FastJsonConfig fastJsonConfig = new FastJsonConfig();
// fastJsonConfig.setCharset(Charset.forName("GBK"));
// fastJsonHttpMessageConverter.setFastJsonConfig(fastJsonConfig);
//
// List<MediaType> mediaTypes = Lists.newArrayList();
// mediaTypes.add(MediaType.valueOf("application/json;charset=GBK"));
// fastJsonHttpMessageConverter.setSupportedMediaTypes(mediaTypes);
//
// HttpMessageConverter<?> converter = fastJsonHttpMessageConverter;
// converters.add(0, converter);
// }
}