java restful中文乱码_使用RestTemplate访问RESTful服务乱码处理
在接口服务开发中,我们经常用到Spring模板类RestTemplate访问restful服务。但RestTemplate处理中文乱码问题比较麻烦。以我们项目Spring版本4.1.3.RELEASE为例,RestTemplate默认构造方法初始化的StringHttpMessageConverter的默认字符集是 ISO-8859-1,所以导致RestTemplate请求的响应内容会出现中文乱码。处理方法可如下:import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;
public class RestTemplateUtil {
public static RestTemplate getInstance() {
RestTemplate restTemplate = new RestTemplate();
// 设置编码
restTemplate.getMessageConverters()
.set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
// 打印日志
restTemplate.setInterceptors(
Collections.singletonList(new LoggingClientHttpRequestInterceptor()));
return restTemplate;
}
}
class LoggingClientHttpRequestInterceptor implements ClientHttpRequestInterceptor {
private final static Logger LOGGER = LoggerFactory.getLogger(LoggingClientHttpRequestInterceptor.class);
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution)
throws IOException {
traceRequest(request, body);
ClientHttpResponse response = execution.execute(request, body);
traceResponse(response);
return response;
}
private void traceRequest(HttpRequest request, byte[] body) throws IOException {
LOGGER.debug("======================request begin========================================");
LOGGER.debug("URI : {}", request.getURI());
LOGGER.debug("Method : {}", request.getMethod());
LOGGER.debug("Headers : {}", request.getHeaders());
LOGGER.debug("Request body: {}", new String(body, "UTF-8"));
LOGGER.debug("=====================request end===========================================");
}
private void traceResponse(ClientHttpResponse response) throws IOException {
//StringBuilder inputStringBuilder = new StringBuilder();
//try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(response.getBody(), "UTF-8"))) {
//String line = bufferedReader.readLine();
//while (line != null) {
//inputStringBuilder.append(line);
//inputStringBuilder.append('\n');
//line = bufferedReader.readLine();
//}
//}
LOGGER.debug("=========================response begin=======================================");
LOGGER.debug("Status code : {}", response.getStatusCode());
LOGGER.debug("Status text : {}", response.getStatusText());
LOGGER.debug("Headers : {}", response.getHeaders());
// WARNING: comment out in production to improve performance
LOGGER.debug("Response body: {}", "WARNING: comment out in production to improve performance");
LOGGER.debug("====================response end==============================================");
}
}
如果其他Spring版本无法按如上方法解决,可运用类加载机制,从根源上解决问题,即重写org.springframework.http.converter.StringHttpMessageConverter.class,将DEFAULT_CHARSET的值改为Charset.forName("UTF-8")。以spring版本4.1.3.RELEASE为例:/**
* Copyright 2002-2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.http.converter;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.util.StreamUtils;
/**
* Implementation of {@link HttpMessageConverter} that can read and write strings.
*
*
By default, this converter supports all media types ({@code */*}),
* and writes with a {@code Content-Type} of {@code text/plain}. This can be overridden
* by setting the {@link #setSupportedMediaTypes supportedMediaTypes} property.
*
* @author Arjen Poutsma
* @since 3.0
*/
public class StringHttpMessageConverter extends AbstractHttpMessageConverter {
public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
private final Charset defaultCharset;
private final List availableCharsets;
private boolean writeAcceptCharset = true;
/**
* A default constructor that uses {@code "ISO-8859-1"} as the default charset.
* @see #StringHttpMessageConverter(Charset)
*/
public StringHttpMessageConverter() {
this(DEFAULT_CHARSET);
}
/**
* A constructor accepting a default charset to use if the requested content
* type does not specify one.
*/
public StringHttpMessageConverter(Charset defaultCharset) {
super(new MediaType("text", "plain", defaultCharset), MediaType.ALL);
this.defaultCharset = defaultCharset;
this.availableCharsets = new ArrayList(Charset.availableCharsets().values());
}
/**
* Indicates whether the {@code Accept-Charset} should be written to any outgoing request.
*
Default is {@code true}.
*/
public void setWriteAcceptCharset(boolean writeAcceptCharset) {
this.writeAcceptCharset = writeAcceptCharset;
}
@Override
public boolean supports(Class> clazz) {
return String.class.equals(clazz);
}
@Override
protected String readInternal(Class extends String> clazz, HttpInputMessage inputMessage) throws IOException {
Charset charset = getContentTypeCharset(inputMessage.getHeaders().getContentType());
return StreamUtils.copyToString(inputMessage.getBody(), charset);
}
@Override
protected Long getContentLength(String str, MediaType contentType) {
Charset charset = getContentTypeCharset(contentType);
try {
return (long) str.getBytes(charset.name()).length;
}
catch (UnsupportedEncodingException ex) {
// should not occur
throw new IllegalStateException(ex);
}
}
@Override
protected void writeInternal(String str, HttpOutputMessage outputMessage) throws IOException {
if (this.writeAcceptCharset) {
outputMessage.getHeaders().setAcceptCharset(getAcceptedCharsets());
}
Charset charset = getContentTypeCharset(outputMessage.getHeaders().getContentType());
StreamUtils.copy(str, charset, outputMessage.getBody());
}
/**
* Return the list of supported {@link Charset}s.
*
By default, returns {@link Charset#availableCharsets()}.
* Can be overridden in subclasses.
* @return the list of accepted charsets
*/
protected List getAcceptedCharsets() {
return this.availableCharsets;
}
private Charset getContentTypeCharset(MediaType contentType) {
if (contentType != null && contentType.getCharSet() != null) {
return contentType.getCharSet();
}
else {
return this.defaultCharset;
}
}
}
java restful中文乱码_使用RestTemplate访问RESTful服务乱码处理相关推荐
- spring resttemplate 中文参数_SpringBoot使用RestTemplate访问第三方接口
养成习惯,先赞后看!!! 前言 相信大家都知道如何在自己的项目里面调用自己的接口,只需要调用自己项目里面接口特定的URL地址就行了,但是如果是调用其他项目的接口呢,这时候如果是直接调用的话,很明显我们 ...
- 【Spring学习】RestTemplate访问Rest服务总结
RestTemplate是Spring提供的用于访问Rest服务的客户端,RestTemplate提供了多种便捷访问远程Http服务的方法,能够大大提高客户端的编写效率.调用RestTemplate的 ...
- python 重命名文件出现乱码_下载的文件名总是「乱码」?这里有各平台的解决方法...
说起「乱码」,没遇到过的电脑用户可能是极少的,尤其在国内中文环境下.暴露年龄的「烫烫烫」系列乱码已经绝迹,现如今遇到的往往是类似「%E9%AB%98%E9%A2%91」和「èªå¨é£è±è½»ä¼¼ ...
- mysql 部分汉字乱码_一次mysql部分汉字乱码解决过程
从Confluence db导出数据在控制台上乱码,在SPRING MVC页面也乱码,如"璟".从confunce应用页面上看,无乱码.到底原因在哪里呢? 由于涉及的层非常多,只能 ...
- 使用RestTemplate访问restful服务时遇到的问题
可以通过通过wireshark抓包,使用Postman发送请求 wireshark是非常流行的网络封包分析软件,功能十分强大.可以截取各种网络封包,显示网络封包的详细信息.使用wireshark的人必 ...
- java 8 中文字体_在java程序中直接使用中文字体文件
在java程序中直接使用中文字体文件.代码中的hb.ttf文件请用你自己的中文字体文件代替 java学习 java培训 软件工程师 如何学习java 学习java哪里好 东方清软java培训 清软国际 ...
- java 庖丁解牛中文分词_庖丁解牛中文分词包
http://code.google.com/p/paoding/ Paoding Analysis摘要 Paoding's Knives 中文分词具有极 高效率 和 高扩展性 .引入隐喻,采用完全的 ...
- java导出数据为乱码_传参导出Excel表乱码问题解决方法
业务场景 先描述一下业务场景,要实现的功能是通过搜索框填写参数,然后点击按钮搜索数据,将搜索框的查询参数获取,附加在链接后面,调导Excel表接口,然后实现导出Excel功能.其实做导Excel表功能 ...
- 学习java的中文网站_学习java的网站有哪些
1.Stack overflow Stack可能是编程界中非常流行的网站了 , 是一个与程序相关的 IT 技术问答网站,用户可以在网站免费提交问题,浏览问题,索引相关内容,在创建主页的时候使用简单的 ...
最新文章
- 玩转数据结构从入门到进阶一
- 车道线检测参考学习资料
- IIS不能发布asp.net 应用程序
- Python外(4)-读写mat文件
- Github出现连接超时
- Hibernate之load和get的差别
- Python中的len函数
- Python XML解析器– ElementTree
- Windows内核的基本概念
- Java 编程语言单词汇总
- Excel统一将小写的金额转为大写汉字金额的操作
- centos8 安装kvm
- 图片压缩-speedpdf免费无损在线压缩图片
- 一个BAT大厂面试者整理的Android面试题目!
- 【C++】set/multiset/map/multimap
- Manacher算法的基础应用:小A的回文串
- 基于Linux搭建一个类似Qik手机录像直播平台(服务器端:feng streaming server + web server,客户端:Android手机应用)
- install xmms
- 一个文本框可能存在哪些漏洞
- 怎样才能快速地将爱奇艺qsv格式转换成mp4视频
热门文章
- visual c语言编译运行结果,Visual Studio 2015编译运行C语言文件问题小结
- Eclipse是否必需要安装jdk,jre
- how many fibs java_How many Fibs?(java)
- 用 Ansible 实现基于 OpenShift (Kubernetes) 的 DevOps
- OpenShift 4 之Istio-Tutorial (9) 访问限流
- 使用DocFx生成文档网站并将其发布到GitHub Pages
- CKEditor 5 v17.0.0 发布,新增表格样式和特殊字符支持
- JDK/Java 14 可能带来什么新特性?
- CSS从大图中抠取小图完整教程(background-position应用)【转】
- 服务器c盘显示0字节可用,c盘0字节可用怎么解决 c盘0字节可用处理方法