retrofit 2.0 如何通过 HttpLoggingInterceptor 打印服务器响应的 json ?

使用 Retrofit 网络请求框架,首先要在 app 的 build.gradle 下添加如下依赖:

compile 'com.squareup.retrofit2:retrofit:2.3.0'
compile 'com.squareup.retrofit2:converter-gson:2.3.0'

然后,创建一个 OkHttp3Utils 工具类:

import android.content.Context;
import android.text.TextUtils;
import com.youyoubaoxian.ua.BuildConfig;
import com.youyoubaoxian.ua.config.LoggingInterceptor;
import java.util.concurrent.TimeUnit;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;

public class OkHttp3Utils {
    private static OkHttpClient okHttpClient = null;
    private static final int DEFAULT_TIMEOUT = 30;
    private static Context mContext;

    public  static OkHttpClient getOkHttpSingletonInstance() {
        if (okHttpClient == null) {
            synchronized (OkHttpClient.class) {
                if (okHttpClient == null) {
                    okHttpClient = new OkHttpClient();
                    //设置合理的超时
                    OkHttpClient.Builder httpBuilder = new OkHttpClient.Builder()
                            .readTimeout(3, TimeUnit.SECONDS)
                            .connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS) //设置连接超时 30秒
                            .writeTimeout(3, TimeUnit.MINUTES)
                            .addInterceptor(new LoggingInterceptor())//添加请求拦截
                            .retryOnConnectionFailure(true);

                    //如果不是在正式包,添加拦截 打印响应json
                    if (BuildConfig.DEBUG) {
                        HttpLoggingInterceptor logging = new HttpLoggingInterceptor(
                                new HttpLoggingInterceptor.Logger() {
                                    @Override
                                    public void log(String message) {
                                        if (TextUtils.isEmpty(message)) return;
                                        String s = message.substring(0, 1);
                                        //如果收到响应是json才打印
                                        if ("{".equals(s) || "[".equals(s)) {
                                            LogUtils.i("收到响应: " + message);
                                        }
                                    }
                                });
                        logging.setLevel(HttpLoggingInterceptor.Level.BODY);
                        httpBuilder.addInterceptor(logging);
                    }
                    okHttpClient = httpBuilder.build();
                }
            }
        }
        return okHttpClient;
    }
}

其中,LoggingInterceptor 如下:

import com.youyoubaoxian.ua.BuildConfig;
import com.youyoubaoxian.ua.utils.LogUtils;
import java.io.IOException;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

public class LoggingInterceptor implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        if (BuildConfig.DEBUG) {
            LogUtils.i(String.format("发送请求 %s on %s%n%s",
                    request.url(), chain.connection(), request.headers()));
        }
        return chain.proceed(request);
    }
}

之后,在 继承于 Application 的 MyApplication 中初始化 Retrofit ,在 onCreate() 中调用 initRetrofit() :

 private static Retrofit retrofit;
 private MyServerInterface serverInterface = null;

private void initRetrofit() {
        OkHttpClient client = OkHttp3Utils.getOkHttpSingletonInstance();

        Gson gson = new GsonBuilder()
                .setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ")
                .setLenient()
                .create();//使用 gson coverter,统一日期请求格式

        retrofit = new Retrofit.Builder()
                .baseUrl(UrlHolder.BASE_URL)
                .client(client)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        serverInterface = retrofit.create(MyServerInterface.class);
    }

 public MyServerInterface getMyServerInterface() {
        return serverInterface;
    }

其中,MyServerInterface 示例如下:

    @GET("url")
    Call getData();

最后,在 Activity 中调用 API:

 MyServerInterface serverInterface = ((MyApplication)getApplicationContext()).getMyServerInterface();
    Call call = serverInterface.getData();
        call.enqueue(new Callback() {
            @Override
            public void onResponse(Call call, Response response) {
                LogUtils.i(TAG, "--> - response => "+ response);
                LogUtils.i(TAG, "--> - response.body => "+ response.body());
            }

            @Override
            public void onFailure(Call call, Throwable t) {
                LogUtils.i(TAG, "-->onFailure - t = " + t);
            }
        });

你可能感兴趣的:(Android)