问题来源
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