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

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条)

报告相同问题?

悬赏问题

  • ¥50 gki vendor hook
  • ¥15 centos7中sudo命令无法使用
  • ¥15 灰狼算法和蚁群算法如何结合
  • ¥15 这是一个利用ESP32自带按键和LED控制的录像代码,编译过程出现问题,请解决并且指出错误,指导如何处理 ,协助完成代码并上传代码
  • ¥20 stm32f103,hal库 hal_usart_receive函数接收不到数据。
  • ¥20 求结果和代码,sas利用OPTEX程序和D-efficiency生成正交集
  • ¥50 adb连接不到手机是怎么回事?
  • ¥20 抓取数据时发生错误: get_mooncake_data() missing 1 required positional argument: 'driver'的问题,怎么改出正确的爬虫代码?
  • ¥15 vs2022无法联网
  • ¥15 TCP的客户端和服务器的互联