retrofit2.0+OkHttpClient 中新增公共参数get/post及网络请求日志打印

需求1:更加统一方便管理公共参数
需求2:方便调试http请求日志,查看请求参数和返回参数

新增一个网络拦截器,代码如下:

LogInterceptor 类:

public class LogInterceptor implements Interceptor {

public static String TAG = "LogInterceptor";

@Override
public okhttp3.Response intercept(Interceptor.Chain chain) throws IOException {
    Request oldRequest = chain.request();
    Request.Builder newRequestBuild;
    String method = oldRequest.method();
    String postBodyString="";
    if("POST".equals(method)){
        FormBody.Builder formBodyBuilder = new FormBody.Builder();
        formBodyBuilder.add("deviceOs", iCommon.DEVICE_OS);
        formBodyBuilder.add("appVersion", Utils.instance().getAppVersionName());
        newRequestBuild = oldRequest.newBuilder();

        RequestBody formBody = formBodyBuilder.build();
        postBodyString = bodyToString(oldRequest.body());
        postBodyString += ((postBodyString.length() > 0) ? "&" : "") + bodyToString(formBody);
        newRequestBuild.post(RequestBody.create(MediaType.parse("application/x-www-form-urlencoded;charset=UTF-8"), postBodyString));
    }else {
        // 添加新的参数
        HttpUrl.Builder commonParamsUrlBuilder = oldRequest.url()
            .newBuilder()
            .scheme(oldRequest.url().scheme())
            .host(oldRequest.url().host())
            .addQueryParameter("deviceOs", iCommon.DEVICE_OS)
            .addQueryParameter("appVersion", Utils.instance().getAppVersionName());
        newRequestBuild = oldRequest.newBuilder()
            .method(oldRequest.method(), oldRequest.body())
            .url(commonParamsUrlBuilder.build());
    }
    Request newRequest = newRequestBuild
        .addHeader("Accept", "application/json")
        .addHeader("Accept-Language", "zh")
        .build();

    long startTime = System.currentTimeMillis();
    okhttp3.Response response = chain.proceed(newRequest);
    long endTime = System.currentTimeMillis();
    long duration = endTime - startTime;
    okhttp3.MediaType mediaType = response.body().contentType();
    String content = response.body().string();
    int httpStatus = response.code();
    StringBuilder logSB = new StringBuilder();
    logSB.append("-------start:"+method+"|");
    logSB.append(newRequest.toString()+"\n|");
    logSB.append(method.equalsIgnoreCase("POST")?"post参数{"+ postBodyString +"}\n|":"");
    logSB.append("httpCode=" + httpStatus + ";Response:" + content+"\n|");
    logSB.append("----------End:" + duration + "毫秒----------");
    Log.d(TAG,logSB.toString());
    return response.newBuilder()
        .body(okhttp3.ResponseBody.create(mediaType, content))
        .build();
}
private static String bodyToString(final RequestBody request) {
    try {
        final RequestBody copy = request;
        final Buffer buffer = new Buffer();
        if (copy != null)
            copy.writeTo(buffer);
        else
            return "";
        return buffer.readUtf8();
    } catch (final IOException e) {
        return "did not work";
    }
}
}

使用方法:

OkHttpClient.Builder builder = new OkHttpClient.Builder();
    builder.retryOnConnectionFailure(false)
        .cookieJar(s_cookieJar)
        .connectTimeout(DEFAULT_NETWORK_TIMEOUT, TimeUnit.MILLISECONDS)
        .readTimeout(DEFAULT_NETWORK_TIMEOUT, TimeUnit.MILLISECONDS)
        .writeTimeout(DEFAULT_NETWORK_TIMEOUT, TimeUnit.MILLISECONDS)
        .addInterceptor(new LogInterceptor());
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 175,046评论 25 709
  • iOS网络架构讨论梳理整理中。。。 其实如果没有APIManager这一层是没法使用delegate的,毕竟多个单...
    yhtang阅读 10,652评论 1 23
  • 上回在《神奇的中医1.0针灸是个什么鬼?》 中咱们简要的讲了一下针灸是怎么来的,但其实只讲了一半,真正的针灸不只是...
    孙蛋蛋阅读 4,668评论 8 9
  • 呆在学校的最后一天,夜晚宿舍楼没几个房间是还亮着灯的。但白天,校园里的人其实不少。 在研究生办公室值班,又坐了一天...
    六月的碎碎念阅读 1,638评论 0 0
  • 一个人身边围绕着很多朋友,天天聚集玩乐。但那只是一时的状态,并不是恒久不变的。每一个人都会有这么一段时光,如果分不...
    喃喃自语S阅读 1,274评论 0 0