spring RestTemplate post 通过body 提交 json 类型,返回值中文是乱码的解决方法

使用 spring 的 RestTemplate post,通过body 提交 json 类型的数据,返回值中文是乱码的解决方法。

下面是伪代码

import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
public class XxxServiceImpl {

	private static final Logger logger = LoggerFactory.getLogger(XxxServiceImpl.class);

	@Autowired
	RestTemplate restTemplate;
	
	@Value("${url}")
	private String url;
	

	@Override
	public void openApiV2(String user, String text) {
		
		//-----此处是 解决乱码 start-----
		List<HttpMessageConverter<?>> converterList = restTemplate.getMessageConverters();
		converterList.remove(1);    //移除StringHttpMessageConverter
		HttpMessageConverter<?> converter = new StringHttpMessageConverter(Charset.forName("UTF-8"));
		converterList.add(1, converter);    //convert顺序错误会导致失败
		restTemplate.setMessageConverters(converterList);
		//-----此处是  解决乱码 end----------
		
	
		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.APPLICATION_JSON);
		
		Map param = buildParam(user, text);//参数
		HttpEntity<Map> request = new HttpEntity<Map>(param, headers);
		
		ResponseEntity<String> tt = restTemplate.postForEntity(url, request, String.class);
		if (tt != null && tt.getStatusCode().is2xxSuccessful()) {
			String str = tt.getBody();
			if (StringUtils.isNotBlank(str)) {
				System.out.println(str)
			}
		}		
	}	
}

你可能感兴趣的:(#,springMVC,Spring,代码片段)