Tutorial by Examples

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. class LoggingInterceptor implements Interceptor { @Override public Response intercept(Interceptor.Chain chain) thr...
private static final Interceptor REWRITE_CACHE_CONTROL_INTERCEPTOR = new Interceptor() { @Override public Response intercept(Interceptor.Chain chain) throws IOException { Response originalResponse = chain.proceed(chain.request()); return originalResponse.newBuilder() .header(&q...
I like to wrap my OkHttp into a class called HttpClient for example, and in this class I have methods for each of the major HTTP verbs, post, get, put and delete, most commonly. (I usually include an interface, in order to keep for it to implement, in order to be able to easily change to a different...
private final OkHttpClient client = new OkHttpClient(); public void run() throws Exception { Request request = new Request.Builder() .url(yourUrl) .build(); Response response = client.newCall(request).execute(); if (!response.isSuccessful()) throw new IOExcept...
private final OkHttpClient client = new OkHttpClient(); public void run() throws Exception { Request request = new Request.Builder() .url(yourUrl) .build(); client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOExcepti...
private final OkHttpClient client = new OkHttpClient(); public void run() throws Exception { RequestBody formBody = new FormBody.Builder() .add("search", "Jurassic Park") .build(); Request request = new Request.Builder() .url("https:...
private static final String IMGUR_CLIENT_ID = "..."; private static final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png"); private final OkHttpClient client = new OkHttpClient(); public void run() throws Exception { // Use the imgur image upload API as ...
Grab via Maven: <dependency> <groupId>com.squareup.okhttp3</groupId> <artifactId>okhttp</artifactId> <version>3.6.0</version> </dependency> or Gradle: compile 'com.squareup.okhttp3:okhttp:3.6.0'

Page 1 of 1