I'm using OkHttp 3 (with retrofit2) and I'm trying to get both cookies and logging to work. The problem is the log shows everything but not the cookies. I have captured the HTTP traffic and the cookie ARE being sent, they are just not logged. I tried debugging the logging interceptor, and indeed, the request appears to have no cookies (although it does have other custom headers) when it reaches the intercept()
call. Any ideas what am I doing wrong?
final Gson gson = new GsonBuilder()
.setDateFormat(JSON_DATE_FORMAT)
.create();
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
CookieManager cookieManager = new CookieManager();
cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
OkHttpClient.Builder okClientBuilder = new OkHttpClient.Builder()
.addInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain
.request()
.newBuilder()
.addHeader("custom-header", Utils.getRandomUUIDForHeader())
.build();
return chain.proceed(request);
}
})
.cookieJar(new JavaNetCookieJar(cookieManager))
.addInterceptor(logging);
if (mock) {
okClientBuilder.addInterceptor(new MockApiInterceptor(context));
}
return new Retrofit
.Builder()
.baseUrl(serverURL)
.client(okClientBuilder.build())
.addConverterFactory(ScalarsConverterFactory.create())
.addConverterFactory(GsonConverterFactory.create(gson))
.build()
.create(DefaultApi.class);
Sample output:
<-- 200 OK http://localhost:53580/login (31ms)
Content-Length: 66
Set-Cookie: JSESSIONID=4b42fc452e6adc55334e65b945c24b8886b127a57786a6cd51de6b3117a58cc9; Path=/
OkHttp-Sent-Millis: 1467298601713
OkHttp-Received-Millis: 1467298601718
{
"status":"OK",
"sessionId":"p8tvdIHxQaON",
"entities":[]
}
<-- END HTTP (66-byte body)
--> GET http://localhost:53580/data http/1.1
custom-header: 663d0354-8a16-471a-bf6d-fb7fdb3d3404
--> END GET
Android OkHttp Logging interceptor Interceptors are used to intercept OkHttp calls. The reason to intercept could be to monitor, rewrite and retry calls. It can be used for outgoing request or incoming response both.
Interceptors, according to the documentation, are a powerful mechanism that can monitor, rewrite, and retry the API call. So, when we make an API call, we can either monitor it or perform some tasks.
So, how can we log the response the call. To, start logging we need to add interceptors in the above OkHttpClient. And as we mentioned , interceptors are used to monitor the API call and it will print the logs which would get generated, in the Logcat of the console.
The logging interceptor runs before cookies have been added to the request. Work around this by using a network interceptor instead of an application interceptor. More guidance is here:
https://github.com/square/okhttp/wiki/Interceptors
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With