之前在跟三方公司做接口对接是最蛋疼的,各种不规范,连ContentType类型都不是UTF-8,所以返回的 信息就蛋疼了,乱码了,更蛋疼的他就不改了。。。。。。。。那怎么办呢。。。。。。。。。。。。。
第一步、配置一个拦截器:
import android.content.Context;
import android.util.Log;
import java.io.IOException;
import java.nio.charset.Charset;
import okhttp3.Headers;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;
import okio.GzipSource;
/**
*
* @author J.query
* @date 2021/6/16
* @email j-query@foxmail.com
* @Description:
*
*/
public class HeaderInterceptor implements Interceptor {
private static final String TAG = "HeaderInterceptor";
private Context context;
public HeaderInterceptor(Context context) {
this.context = context;
}
@Override
public Response intercept(Chain chain) throws IOException {
ResponseBody responseBody = null;
Request original = chain.request();
Response response = chain.proceed(original);
try {
MediaType contentType = responseBody.contentType();
String query = bufferBody(response);
Log.e(TAG, "解密前数据contentType====》${contentType}");
Log.e(TAG, "解密前数据====》${query}");
//数据加密工具(可忽略)
DESUtils des = new DESUtils(SECRET_KEY); // 加密代码
String responseData = des.decrypt(query);
responseBody = ResponseBody.create(MediaType.parse("application/json;charset=UTF-8"), responseData.trim());
} catch (Exception e) {
e.printStackTrace();
}
Log.e(TAG, "解密后数据====》${responseData}");
response = response.newBuilder()
.addHeader("Content-Type", "application/json")
.body(responseBody)
.build();
return response;
}
private String bufferBody(Response response) throws IOException {
Headers headers = response.headers();
ResponseBody responseBody = response.body();
BufferedSource source = responseBody.source();
source.request(Long.MAX_VALUE); // Buffer the entire body.
Buffer buffer = source.buffer();
// 判断是否有压缩
if ("gzip".equalsIgnoreCase(headers.get("Content-Encoding"))) {
GzipSource gzippedResponseBody = null;
try {
gzippedResponseBody = new GzipSource(buffer.clone());
buffer = new Buffer();
buffer.writeAll(gzippedResponseBody);
} finally {
if (gzippedResponseBody != null) {
gzippedResponseBody.close();
}
}
}
return buffer.clone().readString(Charset.forName("UTF-8"));
}
}
第二步、在App初始化网络配置信息
OkHttpClient.Builder builder = new OkHttpClient().newBuilder();
if (BuildConfig.DEBUG) {
HttpLoggingInterceptorM interceptor = setLogInterceptor();//日志拦截器
interceptor.setLevel(HttpLoggingInterceptorM.Level.BODY);
builder.addInterceptor(interceptor);
}
builder.connectTimeout(10, TimeUnit.SECONDS)
//关键代码(测试Interceptor(new HeaderInterceptor(this))这样也是可以的)
.addNetworkInterceptor(new HeaderInterceptor(this))//添加header拦截器
.sslSocketFactory(getSSLFactory(), xtm)
.hostnameVerifier(DO_NOT_VERIFY);
OkHttpClient client = builder.build();
关键看图,返回的数据是UTF-8了。