okhttp返回内容乱码_android retrofit 请求返回String数据中文乱码解决方案

问题来源

focus 应用中核心的部分是,网络请求订阅的xml文件内容,然后解析xml文件存储到本地数据库。

这里网络请求我使用的是retrofit,返回的类型是String,所以使用的是ScalarsConverterFactory的解析器。

*就会出现中文乱码问题。

解决方法

给okhttp添加拦截器

EncodingInterceptor.javapackage com.ihewro.focus.helper;

import com.blankj.ALog;

import com.ihewro.focus.util.StringUtil;

import java.io.IOException;

import java.lang.reflect.Field;

import java.lang.reflect.Modifier;

import java.net.SocketTimeoutException;

import java.util.logging.Logger;

import okhttp3.Headers;

import okhttp3.Interceptor;

import okhttp3.Request;

import okhttp3.Response;

import okhttp3.ResponseBody;

/**

*

 
 

* time : 2019/05/23

* desc :

* version: 1.0

*

*/

public class EncodingInterceptor implements Interceptor {

/**

* 自定义编码

*/

private String encoding;

public EncodingInterceptor(String encoding) {

this.encoding = encoding;

}

@Override public Response intercept(Interceptor.Chain chain) throws IOException {

Request request = chain.request();

Response response = chain.proceed(request);

settingClientCustomEncoding(response);

return response;

}

/**

* setting client custom encoding when server not return encoding

* @param response

* @throws IOException

*/

private void settingClientCustomEncoding(Response response) throws IOException {

setBodyContentType(response);

}

/**

* set body contentType

* @param response

* @throws IOException

*/

private void setBodyContentType(Response response) throws IOException {

ResponseBody body = response.body();

// setting body contentTypeString using reflect

Class extends ResponseBody> aClass = body.getClass();

try {

Field field = aClass.getDeclaredField("contentTypeSt

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值