本文主要是介绍Retrofit2.0 或OKHttp 日志log,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
Retrofit2.0 怎么打印请求到的json字符串和查看log呢?
关键类:HttpLoggingInterceptor
关键代码:
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
httpClient = new OkHttpClient.Builder().addInterceptor(logging).build();
详细代码
public static Retrofit initRetrofit(){OkHttpClient httpClient = new OkHttpClient();if (BuildConfig.DEBUG) {HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
httpClient = new OkHttpClient.Builder().addInterceptor(logging).build();}Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ").create();//使用 gson coverter,统一日期请求格式return new Retrofit.Builder().baseUrl(BaseUtil.getGlivecApiUrl()).addConverterFactory(GsonConverterFactory.create(gson)).client(httpClient).build();}/*** 创建 RetrofitManage 服务** @return ApiService*/public static ApiService createApiService() {return initRetrofit().create(ApiService.class);}
.client(httpClient)属性切莫忘记配置。
retrofit:2.0.0-beta4的依赖:
compile 'com.squareup.retrofit2:retrofit:2.0.0-beta4' // retrofit
compile 'com.google.code.gson:gson:2.5' // gson
compile 'com.squareup.retrofit2:converter-gson:2.0.0-beta4'
compile 'com.squareup.retrofit2:adapter-rxjava:2.0.0-beta4'
compile 'com.squareup.okhttp3:logging-interceptor:3.1.2'
compile 'com.squareup.okhttp3:okhttp:3.1.2'
也可以这么写:
public class RxService {private static final String BASETESTURL = "http://apis.baidu.com/showapi_open_bus/";private static OkHttpClient okHttpClient = new OkHttpClient.Builder().addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY)).build();private static Retrofit retrofit = new Retrofit.Builder().baseUrl(BASETESTURL).client(okHttpClient).addCallAdapterFactory(RxJavaCallAdapterFactory.create()).addConverterFactory(GsonConverterFactory.create()).build();private RxService() {//construct}public static <T> T createApi(Class<T> clazz) {return retrofit.create(clazz);}}
转自:http://blog.csdn.net/jdsjlzx/article/details/51520945
Android学习交流群:523487222
(如果您觉得有用,欢迎加入,一起学习进步)
点击链接加入群【Android学习群】
这篇关于Retrofit2.0 或OKHttp 日志log的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!