后台接口返回数据乱码,Retrofit配置headers无效处理办法

之前在跟三方公司做接口对接是最蛋疼的,各种不规范,连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了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值