OkHttpClient - Real request and response headers log
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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