基于Retrofit的网络请求框架(打印请求参数封装)配合PostMan快速和后台联调

Retrofit2是由Square出品,JackWharton大牛主导开发的一个网络请求框架。

如何让Retrofit打印出请求信息:包括请求网址,入参,出参?这个官方给了一个依赖,可以通过添加依赖

compile 'com.squareup.okhttp3:logging-interceptor:3.10.0'(版本号可自选到最新版本)

HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
            interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
            OkHttpClient.Builder builder = new OkHttpClient.Builder()
                    .connectTimeout(15, TimeUnit.SECONDS)
                    .readTimeout(20, TimeUnit.SECONDS)
                    .writeTimeout(20, TimeUnit.SECONDS)
                    .retryOnConnectionFailure(false)
                    .addInterceptor(interceptor);
            OkHttpClient client = builder.build();
            retrofitInstance = new Retrofit.Builder()
                    .baseUrl(BASEURL)
                    .client(client)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();

通过上面代码将拦截器添加进去。

当然官方给的拦截器给了4个日志过滤类型,可以根据需求自己通过serLevel()方法设置:

public enum Level {
    /** No logs. */
    NONE,
    /**
     * Logs request and response lines.
     *
     * <p>Example:
     * <pre>{@code
     * --> POST /greeting http/1.1 (3-byte body)
     *
     * <-- 200 OK (22ms, 6-byte body)
     * }</pre>
     */
    BASIC,
    /**
     * Logs request and response lines and their respective headers.
     *
     * <p>Example:
     * <pre>{@code
     * --> POST /greeting http/1.1
     * Host: example.com
     * Content-Type: plain/text
     * Content-Length: 3
     * --> END POST
     *
     * <-- 200 OK (22ms)
     * Content-Type: plain/text
     * Content-Length: 6
     * <-- END HTTP
     * }</pre>
     */
    HEADERS,
    /**
     * Logs request and response lines and their respective headers and bodies (if present).
     *
     * <p>Example:
     * <pre>{@code
     * --> POST /greeting http/1.1
     * Host: example.com
     * Content-Type: plain/text
     * Content-Length: 3
     *
     * Hi?
     * --> END POST
     *
     * <-- 200 OK (22ms)
     * Content-Type: plain/text
     * Content-Length: 6
     *
     * Hello!
     * <-- END HTTP
     * }</pre>
     */
    BODY
  }

但是这几种方式都没有打印出请求参数,我们也可以通过根据拦截器源码定制自己的网络请求打印日志,比如我定义的要求打印出网络请求地址,入参,出参,请求时间:

import java.io.IOException;
import java.nio.charset.Charset;

import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okio.Buffer;

import static okhttp3.internal.Util.UTF_8;

/**
 * Created by wangmaobo on 2018/3/29.
 */
public class RetrofitLogInterceptor implements Interceptor {
    public static String TAG = "RetrofitLogInterceptor";

    @Override
    public synchronized okhttp3.Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        long startTime = System.currentTimeMillis();
        okhttp3.Response response = chain.proceed(chain.request());
        long endTime = System.currentTimeMillis();
        long duration = endTime - startTime;
        okhttp3.MediaType mediaType = response.body().contentType();
        String content = response.body().string();
        LogUtil.e(TAG, "请求地址:| " + request.toString());
        printParams(request.body());
        LogUtil.e(TAG, "请求体返回:| Response:" + content);
        LogUtil.e(TAG, "----------请求耗时:" + duration + "毫秒----------");
        return response.newBuilder().body(okhttp3.ResponseBody.create(mediaType, content)).build();
    }


    private void printParams(RequestBody body) {
        Buffer buffer = new Buffer();
        try {
            body.writeTo(buffer);
            Charset charset = Charset.forName("UTF-8");
            MediaType contentType = body.contentType();
            if (contentType != null) {
                charset = contentType.charset(UTF_8);
            }
            String params = buffer.readString(charset);
            LogUtil.e(TAG, "请求参数: | " + params);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

打印结果如下:


另外附上几个跟后台方便调试的工具:

1.PostMan,传送门

2.Json.cn,传送门 :这个是格式化字符串用的,可以把无序的json字符串格式化成一目了然的格式,

用法:将json字符串复制到左侧,右侧就会自动格式化。

猜你喜欢

转载自blog.csdn.net/qq_20089667/article/details/80618997