RestTemplate 发送 formData 中文乱码

spring版本4.2.6

综合网上的案例, 自己修改了部分代码, 最终实现解决中文乱码问题

废话不说直接上代码


    public static String sendRequest(String url, Map body) {
        logger.info("请求数据post =======>> url: {}, 请求数据: {}", url, JSON.toJSONString(body));
        RestTemplate restTemplate = new RestTemplate();

        // 对中文格式数据进行处理 解决中文乱码
        FormHttpMessageConverter fc = new FormHttpMessageConverter();
        List> partConverters = new ArrayList<>();
        partConverters.add(new StringHttpMessageConverter(StandardCharsets.UTF_8));
        partConverters.add(new ResourceHttpMessageConverter());
        fc.setPartConverters(partConverters);
        restTemplate.setMessageConverters(Arrays.asList(fc, new MappingJackson2HttpMessageConverter()));

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        HttpEntity> request = new HttpEntity<>(popHeaders(body), headers);
        //发送请求,设置请求返回数据格式为String
        ResponseEntity responseEntity = restTemplate.postForEntity(url, request, Object.class);
        Object res = responseEntity.getBody();
        String s = JSON.toJSONString(res);
        logger.info("响应数据 =======>> : {}", s);
        return s;
    }

    //组装请求体
    private static MultiValueMap popHeaders(Map body) {
        MultiValueMap map = new LinkedMultiValueMap<>();
        body.forEach((k, v) -> map.put(k, Arrays.asList(v)));
        return map;
    } 
  

参考: https://blog.csdn.net/yyysylvia/article/details/91047409

参考: https://www.cnblogs.com/wangzun/p/7765387.html

你可能感兴趣的:(代码)