使用RestTemplate解决传输过程中的中文乱码问题

private String sendData(String jsonStr, String url) {

        RestTemplate restTemplate = new RestTemplate();
        // 设置restemplate编码为utf-8
        restTemplate.getMessageConverters().set(1,new StringHttpMessageConverter(StandardCharsets.UTF_8));
        MediaType type = MediaType.parseMediaType("application/json;charset=UTF-8");

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(type);
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());

        HttpEntity entity = new HttpEntity(jsonStr);

        
        ResponseEntity responseEntity = restTemplate.postForEntity(url, entity, String.class);
        String returnback = responseEntity.getBody();
        return returnback;
    }

根据项目的实际情况测试通过,如有其他不成功的情况,可自行修改

你可能感兴趣的:(springBoot)