Skip to content

Instantly share code, notes, and snippets.

@Pulimet
Created September 14, 2017 11:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Pulimet/b959dde0301aa6bc524f7762edd50464 to your computer and use it in GitHub Desktop.
Save Pulimet/b959dde0301aa6bc524f7762edd50464 to your computer and use it in GitHub Desktop.
OkHttpClient - Real request and response headers log
public class OkHttpHelper {
public static final String TAG = "OkHttpHelper";
public static final boolean SHOW_NETWORK_LOGS = true;
public static OkHttpClient getOkHttpClient() {
int cacheSize = 10 * 1024 * 1024; // 10 MB
Cache cache = new Cache(getCacheDir(), cacheSize);
return new OkHttpClient.Builder()
.addInterceptor(applicationInterceptor)
.addNetworkInterceptor(networkInterceptor)
.cache(cache)
.build();
}
private static File getCacheDir() {
return new File(Contextor.getInstance().getContext().getCacheDir(), "http");
}
private static final Interceptor applicationInterceptor = new Interceptor() {
@SuppressLint("DefaultLocale")
@Override
public Response intercept(@NonNull Interceptor.Chain chain) throws IOException {
Request request = chain.request();
long t1 = System.nanoTime();
Response response = chain.proceed(request);
long t2 = System.nanoTime();
if (SHOW_NETWORK_LOGS) {
if (response.isSuccessful() && response.networkResponse() != null) {
Log.i(TAG, String.format("%s - %s => Received networkResponse for %s in %.1fms%n%s",
response.networkResponse().code(),
response.networkResponse().message(),
response.networkResponse().request().url(),
(t2 - t1) / 1e6d,
response.networkResponse().headers()));
} else {
Log.e(TAG, "response.isSuccessful() false or response.networkResponse() == null");
}
}
return response;
}
};
private static final Interceptor networkInterceptor = new Interceptor() {
@Override
public Response intercept(@NonNull Chain chain) throws IOException {
if (SHOW_NETWORK_LOGS) {
Log.i(TAG, String.format("Sending request %s Headers: %n%s", chain.request().url(), chain.request().headers()));
}
return chain.proceed(chain.request());
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment