OkHttp Interceptor for Retrofit2 | With Example

This tutorial only focuses on OkHttp Interceptor. If you want to learn how to send a network request with Retrofit from basics read this

In our last post we have learnt how to send a network request with Retrofit on Android. While Retrofit makes sending HTTP requests quite simple it also allows a unique mechanism to monitor and rewrite these requests. This is implemented with the help of OkHttp Interceptor. Intercept – the word means “to obstruct something from reaching its destinations”, similarly Interceptors obstruct a request, rewrite it and then send it to the destinations(server). For example suppose you need all the HTTP requests sent from your app to have authorization token as header. Instead of dynamically adding the same header to all the endpoints as shown here you can simply add a interceptor which will be invoked every time you send a request.

The official explanation for Interceptors is

Interceptors are to observe, modify and potentially short-circuits requests going out and the corresponding responses coming back in. Typically interceptors add, remove, or transform headers on the request  or response.

Interceptors are basically of two types

  • Application Interceptors
    These are high level interceptors which are used to intercept request and response. They are usually used to rewrite headers/query of both request and response. These are definitly invoked once even if the response is fetched from cache.
  • Network Interceptors
    These are low level interceptors used to monitor requested just as it is transmitted over the network. Are very useful to follow redirects and retries and give access to various low level details of the request. These are not invoked if the response is cached.

The diagram below explains the difference between Network and Application Interceptors

interceptors.png

Creating Interceptors

Creating or defining a Interceptor is very simple. You just need to implement the Interceptor interface and override the intercept() method as shown below.  The same interface implementation works for both  NetworkInterceptor and ApplicationInterceptor

private static class CustomInterceptor implements Interceptor {

    @Override
    public Response intercept(Chain chain) throws IOException {
        /*
        chain.request() returns original request that you can work with(modify, rewrite)
        */
        Request request = chain.request();

        // Here you can rewrite the request

        /*
        chain.proceed(request) is the call which will initiate the HTTP work. This call invokes the
        request and returns the response as per the request.
        */
        Response response = chain.proceed(request);

        //Here you can rewrite/modify the response

        return response;
    }
}

 

A call to chain.proceed(request) is a critical part of each interceptor’s implementation. This simple-looking method is where all the HTTP work happens, this is where the request is initiated and a response is fetched to satisfy the request.

Once you have defined your interface you can register it with the OkHttp client as shown below. Now you should register this client with Retrofit.Builder thereby for all your requests OkHttp client will be used and your interceptor will be invoked

OkHttpClient okHttpClient = new OkHttpClient.Builder()
    .addInterceptor(new CustomInterceptor()) // This is used to add ApplicationInterceptor.
    .addNetworkInterceptor(new CustomInterceptor()) //This is used to add NetworkInterceptor.
    .build();

//Defining the Retrofit using Builder
Retrofit retrofit = new Retrofit.Builder()
    .baseUrl(BASE_URL) //This is the onlt mandatory call on Builder object.
    .client(okHttpClient) //The Htttp client to be used for requests
    .addConverterFactory(GsonConverterFactory.create()) // Convertor library used to convert response into POJO
    .build();

 

 

Logging Request and Response

As developers it is very important that we log the requests/responses which are sent and received  from the app. These logs give us details about the headers, response body, request body and various other details which are crucial for debugging any error. Thanks to Interceptors logging all the HTTP operations on Android is very simple.

Retrofit provides us with a Custom Interceptor – HttpLoggingInterceptor which can be registered with OkHttpClient. With this you will be able to print all the logs for the HTTP operations through this client.

HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();

Retrofit retrofit = new Retrofit.Builder()
        .baseUrl("https://backend.example.com")
        .client(client)
        .addConverterFactory(GsonConverterFactory.create())
        .build();

 

Rewriting Requests- Adding/Removing Headers

We have already seen how to define a Custom Interceptor. Now in this section we will define a Custom Interceptor to modify the headers sent with a network request.

private static class RequestInterceptor implements Interceptor {

    @Override
    public Response intercept(Chain chain) throws IOException {
        /*
        chain.request() returns original request that you can work with(modify, rewrite)
        */
        Request originalRequest = chain.request();

        Headers headers = new Headers.Builder()
            .add("Authorization", "auth-value")
            .add("User-Agent", "you-app-name")
            .build();

        Request newRequest = originalRequest.newBuilder()
            .addHeader("Authorization", "auth-value") //Adds a header with name and value.
            .addHeader("User-Agent", "you-app-name")
            .cacheControl(CacheControl.FORCE_CACHE) // Sets this request's Cache-Control header, replacing any cache control headers already present.
            .headers(headers) //Removes all headers on this builder and adds headers.
            .method(originalRequest.method(), null) // Adds request method and request body
            .removeHeader("Authorization") // Removes all the headers with this name
            .build();

        /*
        chain.proceed(request) is the call which will initiate the HTTP work. This call invokes the
        request and returns the response as per the request.
        */
        Response response = chain.proceed(newRequest);

        return response;
    }

}

 

Rewriting Response with OKHttp Interceptor

Similarly, OkHttp Interceptor can be used to rewrite/ modify response from the server. With this you can not only rewrite response headers but also can make changes to the response body.

In the example below we read the response code and build a new response body based on the response code.

private static class ResponseInterceptor implements Interceptor {

    @Override
    public Response intercept(Chain chain) throws IOException {
        // We obtain the response using chain.proceed() API. This invokes the request and return the response
        Response response = chain.proceed(chain.request());
        try {

            JSONObject jsonObject = new JSONObject();

            if (response.code() == 200) {
                jsonObject.put("code", 200);
                jsonObject.put("status", "OK");
                jsonObject.put("message", new JSONObject(response.body().string()));
            } else {
                jsonObject.put("code", 404);
                jsonObject.put("status", "ERROR");
                jsonObject.put("message", new JSONObject(response.body().string()));
            }
            MediaType contentType = response.body().contentType();
            ResponseBody body = ResponseBody.create(contentType, jsonObject.toString());
            return response.newBuilder().body(body).build();
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return response;
    }
}

Android Image Upload Example | Multipart Retrofit2

This tutorial only discusses Android image upload using multipart with Retrofit2. If you want to learn about sending HTTP requests using Retrofit2 from basics read this.

Why use Multipart to Upload Image ?

Before diving deep into Android Image upload, its important to understand some basics of HTTP requests. Most importantly how are different types of data sent to server. POST requests are used to send data to server, this data can either be simple readable text fields or sometimes even non alphanumeric binary data(like image files).  In our last tutorial6 we saw how to send a simple POST request with retrofit. To facilitate sending different types of data we have different methods given below

With application/x-www-form-urlencoded, the body of the HTTP message sent to the server is essentially one giant query string — name/value pairs are separated by the ampersand (&), and names are separated from values by the equals symbol (=). But for each non-alphanumeric byte that exists in one of our values, it’s going to take three bytes to represent it. This is very inefficient for sending large files hence this method cannot be used for sending image files

That’s where  multipart/form-data  comes in. Multipart sends a single object(file) in various parts, each part is separated by a boundary and has some portion of object’s data. Each part also has its own headers like Content-Type, Content-Deposition. Below is a sample representation of multipart request to upload two file a.txt and a.html

POST / HTTP/1.1
[[ Less interesting headers ... ]]
Content-Type: multipart/form-data; boundary=---------------------------735323031399963166993862150
Content-Length: 834

-----------------------------735323031399963166993862150
Content-Disposition: form-data; name="text1"

text default
-----------------------------735323031399963166993862150
Content-Disposition: form-data; name="text2"

aωb
-----------------------------735323031399963166993862150
Content-Disposition: form-data; name="file1"; filename="a.txt"
Content-Type: text/plain

Content of a.txt.

-----------------------------735323031399963166993862150
Content-Disposition: form-data; name="file2"; filename="a.html"
Content-Type: text/html

<!DOCTYPE html><title>Content of a.html.</title>

-----------------------------735323031399963166993862150
Content-Disposition: form-data; name="file3"; filename="binary"
Content-Type: application/octet-stream

aωb
-----------------------------735323031399963166993862150--

 

This efficiency of sending single file in multiple parts is the reason most of the browsers use Multipart to upload files. Retrofit is one of the few network libraries which has built in support for Multipart. This enables you  to upload any files from your app without worrying of any of the internal details of Multipart.

Android Image Upload

In the following example we will be uploading a Image file to Server using Multipart with Retrofit2. As per the scope of this example we will only cover how to upload a image/file on server but if you want to first learn how to pick image from gallery/camera please read this example

Step 1 : Add Gradle dependencies

implementation 'com.squareup.retrofit2:retrofit:2.3.0'
implementation 'com.squareup.retrofit2:converter-gson:2.3.0'

Step 2 : Create Retrofit Instance

Create a class NetworkClient.java  to retrieve the Retrofit object anywhere in your application. This instance will be used to send the HTTP request from your app.

public class NetworkClient {

    private static final String BASE_URL = "";
    private static Retrofit retrofit;

    public static Retrofit getRetrofitClient(Context context) {

        if (retrofit == null) {
            OkHttpClient okHttpClient = new OkHttpClient.Builder()
                    .build();
            retrofit = new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .client(okHttpClient)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();

        }

        return retrofit;
    }
    
}

Step 3 : Define the Upload API

We know that with Retrofit2, interface methods are used to  define the APIs with which the app will be interacting. Therefore for uploading an image we define the following API. Note the use of @Multipart and @Part

ublic interface UploadAPIs {
    @Multipart
    @POST("/upload")
    Call<ResponseBody> uploadImage(@Part MultipartBody.Part file, @Part("name") RequestBody requestBody);
}

 

@Multipart 
Denotes that the request body is multi-part. Parts should be declared as parameters and annotated with @Part.

@Part
This denotes a single part of Multipart request. The parameter on which this type exists will be processed in three ways

  • If the parameter type is MultipartBody.Part the contents will be used directly. Part name is not required with the annotation (i.e., @Part MultipartBody.Part part).
  • If the parameter  type is RequestBody the value will be used directly with its content type. Supply the part name in the annotation (e.g., @Part("foo") RequestBody foo).
  • Other object types will be converted to an appropriate representation by using a converter. Supply the part name in the annotation (e.g., @Part("foo") Image photo).

 

Step 4 : Uploading an Image

Now comes most important part- Uploading a File. Input parameter to this method is a simple image file path. As already mentioned if you want to learn how to get file path of the images from gallery/camera read this tutorial

  • Using the file path we create a file object and then create a request body with that image file. Now with the request body we create a MultipartBody.Part by passing file name and part name as shown in the snippet below. This MultipartBody.Part is sent to Retrofit to initiate image upload
  • We can even send some text fields along with the image. Make sure server is able to handle all tha parts that you are sending. Since this is a demo example I am just sending a sample description text request body along with the image.
  • Both  the text and image are sent as parts along with the mutipart requests

 

private void uploadToServer(String filePath) {
     Retrofit retrofit = NetworkClient.getRetrofitClient(this);

     UploadAPIs uploadAPIs = retrofit.create(UploadAPIs.class);

     //Create a file object using file path
     File file = new File(filePath);

     // Create a request body with file and image media type
     RequestBody fileReqBody = RequestBody.create(MediaType.parse("image/*"), file);

     // Create MultipartBody.Part using file request-body,file name and part name 
     MultipartBody.Part part = MultipartBody.Part.createFormData("upload", file.getName(), fileReqBody);

     //Create request body with text description and text media type
     RequestBody description = RequestBody.create(MediaType.parse("text/plain"), "image-type");

     // 
     Call call = uploadAPIs.uploadImage(part, description);

     call.enqueue(new Callback() {
         @Override
         public void onResponse(Call call, Response response) {

         }

         @Override
         public void onFailure(Call call, Throwable t) {

         }
     });

 }

Conclusion

This finishes our fully functional Android Image Upload Example, but in software development just getting something working is not enough. One of the major characteristic of a good programmer is that he writes clean code. And the best tips and guidelines for clean code are mentioned in this book by noted software expert Robert C. Martin. It is a must read for every software engineer.


If you are new to Android you should definitely go through the list of Android examples here. It is a must read for every Android Developer
sexy Indian girls

Android Example : HTTP GET, POST Request with Retrofit

In our last tutorial we discussed about how to send a network request using Volley Library, while Volley is a widely used network library for basic HTTP operations there is one more library which is quite popular among Android developers- Retrofit. In fact many developers prefer Retrofit over Volley due to its ease of use, performance, extensibility etc.

Retrofit is basically an HTTP client for Android and Java developed by the awesome folks at Square. What makes it unique is that with Retrofit you don’t need to worry about parsing the response – meaning de-serialization is handled in the background itself, you just need to configure any convertor library (GSON, Jackson etc). Retrofit uses OkHttp by default for HTTP operations.

In this example we will develop an application which will send a network request with Retrofit and display the response. We will be using OpenWeather API to fetch current weather details. Its a free API service which provider number of APIs to fetch weather details anywhere on the Globe, you just need to register to obtain the API key. Read this for more

API:
https://api.openweathermap.org/data/2.5/weather?q=London,uk

Continue reading

Retrofit Android Example : Sending HTTP GET, POST Request

In our last tutorial we discussed about how to send a network request using Volley Library, while Volley is a widely used network library for basic HTTP operations there is one more library which is quite popular among Android developers- Retrofit. In fact many developers prefer Retrofit over Volley due to its ease of use, performance, extensibility etc.

Retrofit is basically an HTTP client for Android and Java developed by the awesome folks at Square. It uses OKHttp by default for network operations. What makes it unique is that with Retrofit you don’t need to worry about parsing the response – meaning de-serialization is handled in the background itself. You just need to configure any convertor library (GSON, Jackson etc) and the job is done.

In this example we will develop an application which will send a network request with Retrofit and display the response. We will be using OpenWeather API to fetch current weather details. Its a free API service which provides a number of APIs to fetch weather details anywhere on the Globe. You just need to register to obtain the API key. Read this for more

API:
https://api.openweathermap.org/data/2.5/weather?q=London,uk

Continue reading