此物最相思Hu 2017-02-09 05:03 采纳率: 100%
浏览 3848
已采纳

Spring restTemplate 参数乱码

Spring restTemplate 参数乱码

客户端代码:

public static RestTemplate creatTemplate(){
        RestTemplate restTemplate=new RestTemplate();

        FormHttpMessageConverter fc = new FormHttpMessageConverter();

        StringHttpMessageConverter s = new StringHttpMessageConverter(StandardCharsets.UTF_8);

        List<HttpMessageConverter<?>> partConverters = new ArrayList<HttpMessageConverter<?>>();
        partConverters.add(s);
        partConverters.add(new ResourceHttpMessageConverter());
        fc.setPartConverters(partConverters);

        MappingJackson2HttpMessageConverter jsonMessageConverter = 
        new MappingJackson2HttpMessageConverter();
        // Add supported media type
        List<MediaType> supportedMediaTypes = new ArrayList<MediaType>();
        supportedMediaTypes.add(new MediaType("text", "plain"));
        supportedMediaTypes.add(new MediaType("charset", "utf-8"));
        supportedMediaTypes.add(new MediaType("text", "html"));
        supportedMediaTypes.add(new MediaType("application", "json"));
        jsonMessageConverter.setSupportedMediaTypes(supportedMediaTypes);
        restTemplate.getMessageConverters().addAll(Arrays.asList(fc, jsonMessageConverter));
        ClientHttpRequestInterceptor interceptor=   new ClientHttpRequestInterceptor() {   
            @Override   
            public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution)   
            throws IOException {   
                    HttpRequestWrapper wrapper = new HttpRequestWrapper(request);   
                    MediaType mt=MediaType.valueOf("application/json;charset=utf-8"); 
                    System.out.println(mt.getCharSet());
                    wrapper.getHeaders().setContentType(mt);   
                    wrapper.getHeaders().setAccept(Collections.singletonList(new MediaType("application", "json")));  
                    wrapper.getHeaders().setAcceptCharset(Collections.singletonList(Charset.forName("utf-8")));
                    return execution.execute(wrapper, body);   
                }

            };  
        restTemplate.setInterceptors(Collections.singletonList(interceptor));
        return restTemplate;
    }


    public static void main(String[] args) {
        JSONObject js=new JSONObject();
        JSONObject appSign=new JSONObject();
        appSign.put("appkey", "xunyukeji");
        appSign.put("timestamp", "12345678900");
        appSign.put("sign", "F206BEB57018BDA4B2369CE998A5F1C5");
        js.put("type", "S");
        js.put("apiSign", appSign);
        JSONArray list=new JSONArray();
        JSONObject item=new JSONObject();
        item.put("message", "订单发货日期2017-01-10 16:13:31");
        item.put("status", "S");
        item.put("code", "shunfeng");
        item.put("tradeNum", "5455454");
        item.put("expressName", "顺丰快递");
        list.add(item);
        js.put("list", list);
        RestTemplate restTemplate=creatTemplate();

        JSONObject result=restTemplate.postForObject("http://192.168.0.126/webapp/wcs/stores/servlet/SBNUpdateOrderStatusCmd", js.toString(), JSONObject.class);
        System.out.println(result.toString());


    }

服务端参数处理代码:

 public String getParams(HttpServletRequest request) throws IOException{
        Enumeration<String> names = request.getHeaderNames();  
        while (names.hasMoreElements()) {  
            String name = names.nextElement();  
            System.out.println("["+name + " : " + request.getHeader(name) + "]");  
        }  
        request.setCharacterEncoding("utf-8");
        // 读取请求内容
        BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream()));
        String line = null;
        StringBuilder sb = new StringBuilder();
        while((line = br.readLine())!=null){
            sb.append(line);
        }
        // 将资料解码
        String reqBody = new String(sb.toString().getBytes("ISO-8859-1"),"UTF-8");
        return  reqBody;
    }

服务端接收的请求头和处理后的参数

 [17-2-9 12:53:32:875 CST] 000000ab SystemOut     O [Accept : application/json]
[17-2-9 12:53:32:876 CST] 000000ab SystemOut     O [Content-Type : application/json;charset=utf-8]
[17-2-9 12:53:32:876 CST] 000000ab SystemOut     O [Accept-Charset : utf-8]
[17-2-9 12:53:32:876 CST] 000000ab SystemOut     O [User-Agent : Java/1.7.0_79]
[17-2-9 12:53:32:876 CST] 000000ab SystemOut     O [Host : 192.168.0.126]
[17-2-9 12:53:32:877 CST] 000000ab SystemOut     O [Connection : keep-alive]
[17-2-9 12:53:32:877 CST] 000000ab SystemOut     O [Content-Length : 235]
[17-2-9 12:53:33:436 CST] 000000ab SystemOut     O 2017-02-09 12:53:33,434 INFO [updateOrder] - 修改订单接收参数{"type":"S","apiSign":{"appkey":"xunyukeji","timestamp":"12345678900","sign":"F206BEB57018BDA4B2369CE998A5F1C5"},"list":[{"message":"??????2017-01-10 16:13:31","status":"S","code":"shunfeng","tradeNum":"5455454","expressName":"????"}]}
[17-2-9 12:53:34:102 CST] 000000ab SystemOut     O F206BEB57018BDA4B2369CE998A5F1C5
[17-2-9 12:53:34:103 CST] 000000ab SystemOut     O 2017-02-09 12:53:34,102 INFO [updateOrder] - 密钥验证成功

可以看到中文部分都是乱码的,客户端和服务端的编码格式都是UTF-8,而且同样的代码服务端用main方法httpclient调用,参数处理后却是正常的

  • 写回答

2条回答 默认 最新

  • 林夕68 2017-02-09 05:42
    关注

    你调用服务器端代码先编码,服务器端解析

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 MddBootstrapInitialize2失败
  • ¥15 LCD Flicker
  • ¥15 Spring MVC项目,访问不到相应的控制器方法
  • ¥15 esp32在micropython环境下使用ssl/tls连接mqtt服务器出现以下报错Connected on 192.168.154.223发生意外错误: 5无法连接到 MQTT 代理,如何解决?
  • ¥15 关于#genesiscsheel#的问题,如何解决?
  • ¥15 Android aidl for hal
  • ¥15 STM32CubeIDE下载程序报错
  • ¥15 微信好友如何转变为会员系统?(相关搜索:小程序)
  • ¥15 c# 直接使用c++ 类库文件
  • ¥15 一个主机电脑有两个显示器,当前有两个软件主体是网页html打包的exe程序,如何通过cmd命令bat同时打开软件一个在主屏幕显示,另外一个软件在2副屏幕上显示