Retrofit2/OkHttp3拦截器Interceptor获取完整http请求和响应数据

Retrofit2/OkHttp3拦截器Interceptor获取完整http请求和响应数据

引入:

    implementation 'com.squareup.retrofit2:retrofit:2.5.0'
    implementation 'com.squareup.okhttp3:logging-interceptor:3.12.2'
package com.example.demo;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Path;

public interface GetService {
    @GET("article/month/{year}/{month}")
    Call getResult(@Path("year") String year, @Path("month") String month);
}

package com.example.demo;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;

import okhttp3.OkHttpClient;
import okhttp3.ResponseBody;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

public class MainActivity extends AppCompatActivity {
    private String TAG = "OkHttp日志";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //日志显示级别。
        HttpLoggingInterceptor.Level level = HttpLoggingInterceptor.Level.BODY;

        //http拦截器。
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
            @Override
            public void log(String message) {
                Log.d(TAG, message);
            }
        });
        loggingInterceptor.setLevel(level);

        //定制OkHttp。
        OkHttpClient.Builder okHttpClientBuilder = new OkHttpClient
                .Builder();

        okHttpClientBuilder.addInterceptor(loggingInterceptor);

        Retrofit retrofit = new Retrofit.Builder()
                .client(okHttpClientBuilder.build()) //为Retrofit增加定制的OkHttp客户端,主要提供日志输出功能。
                .baseUrl("https://blog.csdn.net/zhangphil/")
                .build();

        GetService getService = retrofit.create(GetService.class);
        Call mCall = getService.getResult("2019","03");

        mCall.enqueue(new Callback() {
            @Override
            public void onResponse(Call call, Response response) {
                try {
                    Log.d(TAG + "返回结果", response.body().string());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Call call, Throwable t) {

            }
        });
    }
}

输出http日志:

Retrofit2/OkHttp3拦截器Interceptor获取完整http请求和响应数据_第1张图片

 

OkHttp拦截器的版本在此查得:

https://mvnrepository.com/artifact/com.squareup.okhttp3/logging-interceptor

 

注意:

在Retrofit的约定中,接口定义的@GET里面的路径,被替换的参数不能包含 / ,只能传入单个变量。比如本例,打算请求2019/03月份文章,只能分成两个参数year和month一一替换,而不能只设置一个参数比如time,把time替换成2019/04。

你可能感兴趣的:(Java,Android,http,Android,OkHttp网络技术)