Retrofit2.0 How to print the requested JSON string and view the log?
Key class: Httplogginginterceptor
Key code:
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();logging.setLevel(HttpLoggingInterceptor.Level.BODY);httpClient = new OkHttpClient.Builder().addInterceptor(logging).build();
Detailed code:
Public StaticRetrofitInitretrofit() {Okhttpclient httpClient =NewOkhttpclient ();if(buildconfig.debug) {Httplogginginterceptor logging =NewHttplogginginterceptor (); Logging.setlevel (HttpLoggingInterceptor.Level.BODY); httpClient =NewOkhttpclient.builder (). Addinterceptor (logging). build (); } Gson Gson =NewGsonbuilder (). Setdateformat ("Yyyy-mm-dd ' T ' HH:mm:ssZ"). Create ();//Use Gson Coverter, unified date Request Format return NewRetrofit.builder (). BASEURL (Baseutil.getglivecapiurl ()). Addconverterfactory (Gsonconverterfa Ctory.create (Gson)). Client (httpClient). build (); }/** * Create retrofitmanage Service * * @return apiservice */ Public StaticApiserviceCreateapiservice() {returnInitretrofit (). Create (Apiservice.class); }
The. Client (HttpClient) attribute does not forget to configure.
RETROFIT:2.0.0-BETA4 's dependence:
‘com.squareup.retrofit2:retrofit:2.0.0-beta4‘// retrofit‘com.google.code.gson:gson:2.5‘// gson‘com.squareup.retrofit2:converter-gson:2.0.0-beta4‘‘com.squareup.retrofit2:adapter-rxjava:2.0.0-beta4‘‘com.squareup.okhttp3:logging-interceptor:3.1.2‘‘com.squareup.okhttp3:okhttp:3.1.2‘
You can also write this:
Public classRxservice {Private StaticFinal String Basetesturl ="http://apis.baidu.com/showapi_open_bus/";Private StaticOkhttpclient okhttpclient =NewOkhttpclient.builder (). Addinterceptor (NewHttplogginginterceptor (). SetLevel (HttpLoggingInterceptor.Level.BODY)). Build ();Private StaticRetrofit Retrofit =NewRetrofit.builder (). BASEURL (Basetesturl). Client (okhttpclient). Addcalladapterfactory (RXJ Avacalladapterfactory.create ()). Addconverterfactory (Gsonconverterfactory.create ()). build ();Private Rxservice() {//construct} Public Static<T> TCreateapi(Class<t> clazz) {returnRetrofit.create (Clazz); }}
Android Retrofit2.0 View Log and JSON strings (Httplogginginterceptor)