OkHttp源码解析(三)OkHttp自定义拦截器使用

HEAD动态添加

public class TokenInterceptor implements Interceptor {
    private static final String TAG = "TokenInterceptor";

    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        String url = request.url().toString().split("\\?")[0];
        // 如果当前url是这个项目中的(是否以BaseUrl开头的)
        // 不是登录和握手url(这些url不需要token的)
        if (url.startsWith(IApi.getTerminalBaseUrl()) && !url.contains("Login.psp") && !url.contains("ShakeHand.psp")) {
            String token = request.header("Authorization");
            Log.d("TokenInterceptor", "TokenInterceptor token = " + token);

            // 拦截这个url是否有token
            if (TextUtils.isEmpty(token)) {
                // 每次登录成功会把token额外存起来
                String newToken = AppState.INSTANCE.getTerminalToken();
                // token是空,重新进行登录
                if (TextUtils.isEmpty(newToken)) {
                    newToken = ApiHelper.refreshToken(false);
                }

                // token不为空,构造request请求增加头
                if (!TextUtils.isEmpty(newToken)) {
                    request = chain.request().newBuilder().header("Authorization", newToken).build();
                }
            }
        }
        Response response = chain.proceed(request);
        // 认证失败
        if(isTokenExpired(response)){
            // 清空token存储容器
            AppState.INSTANCE.setTerminalToken(null)
            // 重新进行登录
            val newToken = ApiHelper.refreshToken(false)

            if (!TextUtils.isEmpty(newToken)) {
                request = chain.request().newBuilder().header("Authorization", newToken).build()
                return chain.proceed(request)
            }
        }
        
        return response;
    }
    
    private boolean isTokenExpired(Response response) {
        // 认证失败,可以根据各个公司的服务器错误码进行更改
        if (response.code() == 401) {
            return true;
        }
        return false;
    }
}

请求体数据加密

通过自定义拦截器捕获到请求进行加密,响应进行解密,以Base64加解密为例。
Base64加解密工具

public class Base64Util {
    // 编码
    public static String getBase64(String str) {
        String result = "";
        if (str != null) {
            try {
                result = new String(Base64.encode(str.getBytes("utf-8"), Base64.NO_WRAP), "utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    // 解码
    public static String getFromBase64(String str) {
        String result = "";
        if (str != null) {
            try {
                result = new String(Base64.decode(str, Base64.NO_WRAP), "utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        return result;
    }
}

自定义拦截器

public class TestInterceptor implements Interceptor {

    @Override
    public Response intercept(Chain chain) throws IOException {
        //返回request
        Request request = chain.request();
        RequestBody oldRequestBody = request.body();

        if (oldRequestBody != null) {
            MediaType mediaType = oldRequestBody.contentType();
            Buffer requestBuffer = new Buffer();
            oldRequestBody.writeTo(requestBuffer);
            String oldBodyStr = requestBuffer.readUtf8();
            requestBuffer.close();

            Log.e("MainActivity", "原始数据: " + oldBodyStr);
            String newBodyStr = Base64Util.getBase64(oldBodyStr);
            RequestBody newBody = RequestBody.create(mediaType, newBodyStr);
            //构造新的request
            request = request.newBuilder()
                    .header("Content-Type", newBody.contentType().toString())
                    .header("Content-Length", String.valueOf(newBody.contentLength()))
                    .method(request.method(), newBody)
                    .build();
            Log.e("MainActivity", "加密后数据: " + newBodyStr + ",type: " + newBody.contentType().toString() + ",length: " + String.valueOf(newBody.contentLength()));
        }

        //返回response
        Response response = chain.proceed(request);

        //isSuccessful () ; 如果代码在[200..300]中,则返回true,这意味着请求已成功接收、理解和接受。
        if (response.code() == 200) {
            //返回ResponseBody
            ResponseBody responseBody = response.body();
            if (responseBody != null) {
                try {
                    //获取bodyString
                    BufferedSource source = responseBody.source();
                    source.request(Long.MAX_VALUE);
                    Buffer buffer = source.buffer();
                    Charset charset = Charset.forName("UTF-8");
                    MediaType contentType = responseBody.contentType();
                    if (contentType != null) {
                        charset = contentType.charset(charset);
                    }
                    String bodyString = buffer.clone().readString(charset);

                    //我这里是base64解码  具体情况自己定义
                    //base64解码
                    String responseData = new String(Base64Util.getFromBase64(bodyString));
                    //生成新的ResponseBody
                    ResponseBody newResponseBody = ResponseBody.create(contentType, responseData.trim());
                    //response
                    response = response.newBuilder().body(newResponseBody).build();
                    Log.e("MainActivity", "解密后数据: " + responseData);

                } catch (IOException e) {
                    //如果发生异常直接返回
                    e.printStackTrace();
                    return response;
                }
            } else {
                Log.i("MainActivity", "onHttpResultResponse: 响应体为空");
            }
        }

        return response;
    }
}

URL重定向

更换网络请求Url,如果只是访问服务器地址变了,可以将所有网络请求前面的服务器地址抽成BaseUrl,统一进行更改。拦截器主要适用于path也进行更改的情况。
拦截器代码

public class TestInterceptor implements Interceptor {

    private String newHost = "172.16.28.34";
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        HttpUrl url = request.url();
        // http://172.16.40.57/api/login?userName=ceshi&userPassword=123456
        String scheme = url.scheme();
        String host = url.host();
        String path = url.encodedPath();
        String query = url.encodedQuery();

        // scheme: http,host: 172.16.40.57,path: /api/login,query: userName=ceshi&userPassword=123456
        Log.e("MainActivity","scheme: "+scheme+",host: "+host+",path: "+path+",query: "+query);
        String newUrl = new StringBuffer().append(scheme).append("://").append(newHost).append(path).append("?").append(query).toString();

        Request.Builder builder = request.newBuilder()
                .url(newUrl);

        return chain.proceed(builder.build());
    }
}

请求日志抓取

需要进行关联

 implementation 'com.squareup.okhttp3:logging-interceptor:3.9.0'

当然也可以自定义日志拦截器,这里为了方便,直接用自带的日志拦截器。

HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
    @Override
    public void log(String message) {
        if (MLog.canPrintI()) {
            MLog.i(TAG, message);
        }
    }
});
//常见的所有请求全部打印,或者Debug打印BODY,Release打印BASIC
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
builder.addInterceptor(interceptor);

关于日志级别的level

NONE
没有日志输出
BASIC
日志会输出请求类型,请求地址,请求大小,响应码,响应大小。
HEADERS
输出请求和响应的头信息,请求类型,请求地址,响应码。
BODY
输出请求和响应的头信息和内容。

模拟数据

这种一般适用于服务器开发晚于客户端,可以用来打桩调试,已经知道接口字段名字和类型,模拟服务器数据。

public class MockInterceptor implements Interceptor {
    private static final String TAG = "MockInterceptor";

    @Override
    public Response intercept(Chain chain) throws IOException {
        Response.Builder responseBuilder = (new Response.Builder()).code(200).message("").request(chain.request()).protocol(Protocol.HTTP_1_1).addHeader("content-type", "application/json");
        Request request = chain.request();
        String url = request.url().toString().split("\\?")[0];
        Log.d("MockInterceptor", "MockInterceptor url = " + url);
        Response response;
        String body;

        if (url.equals(IApi.getTerminalBaseUrl() + "GetLanCfg.psp")) {
            body = this.getLanCfg();
            responseBuilder.body(ResponseBody.create(MediaType.parse("application/json"), body.getBytes()));
            response = responseBuilder.build();
        }else{
            response = chain.proceed(request);
        }

        return response;
    }

    private String getLanCfg() {
        BaseTerminalResponse baseResponse = new BaseTerminalResponse();
        NetWorkCfg cfg = new NetWorkCfg();
        baseResponse.code = 0;
        cfg.setIpv4("192.168.1.1");
        cfg.setNetMask("255.255.255.0");
        cfg.setSecondDns("200.96.113.2");
        cfg.setFirstDns("200.96.25.3");
        cfg.setDnsMode(1);
        baseResponse.data = cfg;
        return JsonUtil.parseObject2Str(baseResponse);
    }
}

参考

OkHttp 拦截器的一些骚操作

你可能感兴趣的:(OkHttp源码解析(三)OkHttp自定义拦截器使用)