1. 程式人生 > >給Retrofit新增列印請求地址和返回結果

給Retrofit新增列印請求地址和返回結果

步驟

1、匯入庫

  1. compile 'com.squareup.retrofit2:retrofit:2.1.0'

  2. compile 'com.squareup.retrofit2:converter-gson:2.1.0'

  3. compile 'com.squareup.okhttp3:logging-interceptor:3.4.1'

2、初始化HttpLoggingInterceptor

HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {

@Override

public void log(String message) {

//列印retrofit日誌

Log.i("RetrofitLog","retrofitBack = "+message);

}

});

loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

也可以新增全域性的請求頭,因為可以新增多個攔截器

Interceptor interceptor=new Interceptor() {
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request builder = chain.request().newBuilder()
                .addHeader("token",你的ToKen)
                .build();
  return chain.proceed(builder);
    }
};

3、配置okhttp

client = new OkHttpClient.Builder()

.cache(cache)

.addInterceptor(loggingInterceptor)

.addInterceptor(interceptor)

.connectTimeout(mTimeOut, TimeUnit.SECONDS)

.readTimeout(mTimeOut, TimeUnit.SECONDS)

.writeTimeout(mTimeOut, TimeUnit.SECONDS)

.build();

4、配置retrofit

Retrofit retrofit = new Retrofit.Builder()
.baseUrl(userCenter).client(client)
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.build();