以下代码调用某接口时出现乱码:
HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.add("Content-Type","application/json;charset=utf-8"); org.springframework.http.HttpEntity<String> httpEntity = new org.springframework.http.HttpEntity<>(param,httpHeaders); RestTemplate restTemplate = new RestTemplate(); ResponseEntity<String> forEntity = restTemplate.postForEntity(url,httpEntity,String.class);//此处三个参数分别是请求地址、请求体以及返回参数类型 String result = forEntity.getBody();
第一种解决方案:
从别的大神那里了解到,正是这行代码,把结果序列化为String类型,就会乱码。整改的方案就是把String换成实体类,因为转化为String和实体,内部使用的转换器不同,如下:
ResponseEntity<BaseResult> forEntity1 = restTemplate.postForEntity(url,httpEntity,BaseResult.class);第二种解决方案: 清除原来的转换器,添加新的转换器
StringHttpMessageConverter stringHttpMessageConverter = new StringHttpMessageConverter(); stringHttpMessageConverter.setWriteAcceptCharset(false); restTemplate.getMessageConverters().clear(); restTemplate.getMessageConverters().add(stringHttpMessageConverter);
标签:String,解决方案,RestTemplate,乱码,restTemplate,new,httpHeaders From: https://www.cnblogs.com/shalen/p/18175176