Retrofit Tutorial in Android – Part 3 Request Headers

Retrofit Tutorial - Request Headers

Last Updated on April 24, 2018 by Aram

We have come to the 3rd and last part of the Retrofit tutorial in Android, which is passing HTTP request headers using Retrofit.

If you are new to Retrofit, I recommend that you read the previous 2 tutorials in the series, you can find the links below, otherwise just continue exploring this tutorial.

Retrofit Tutorial in Android – Part 1 Introduction

Retrofit Tutorial in Android – Part 2 POST Requests

In HTTP-based Web Services, we sometimes have to pass extra details when doing API requests. Such details will neither be passed through the URL itself or query strings, nor via the request body. In this case, we will have to pass them via the so called Request Headers.

Headers can be related to defining response type, request type, authorization, language and many others. Please refer to Wikipedia’s page for a full list of HTTP Headers.

In this tutorial, we will learn 2 ways to pass the HTTP request headers, either via Retrofit’s annotations or via an intercepter. It is important to notice that the interceptor methodology is not something specific to Retrofit, but it comes from the OkHttp library, which is the core library underneath Retrofit.

To better explain how can we pass headers using Retrofit, I thought that the best example would be doing an Authenticated API Call to Oxford Dictionaries.

First thing that we need to do is to obtain API Key and password from the Developer section of the Oxford Dictionaries website.

Open the website, click on Get Your API Key , choose the plan you want and then follow the registration process. Once you are logged in, you can go into API Credentials sections and generate your API Key. You can notice the base URL to do the HTTP Request and the Application ID. Do not use my ID and Key, just go to the Oxford Dictionaries website, sign up and obtain your free API key. It is super easy and straightforward.

With each HTTP Request from your app to Oxford Dictionaries API, you should pass the correct Application ID and the API Key. Failure to provide any of which will result in an HTTP 403 Authentication Failed Message.

Now that we have the Application ID and the API Key, let’s go back to Android Studio, and start writing our app that will do authenticated requests to Oxford Dictionaries API, and display meanings for words entered by the user.

We will go through the creation steps quickly, as these have been explained in details in the first tutorial of the Retrofit Tutorial in Android series.

From Android Studio, start with a blank project. Open Gradle file and reference the retrofit and retrofit converter-gson libraries.

Sync the project to install the retrofit libraries and dependencies. And don’t forget to include the INTERNET Permission into your manifest file.

Before we create Retrofit Interface, we need to prepare the data models to receive the response from the Oxford Dictionaries Entries API.

If you try calling the the dictionary entries endpoint using your app_id and app_key, using any of your preferred tools to do HTTP API Calls such as Oxford Dictionaries API Documentation itself or Postman App or hurl.it, you should get the following JSON response, assuming that the URL is: https://od-api.oxforddictionaries.com/api/v1/entries/en/oxford

For this we need to create a set of java classes (POJO) , which stands for Plain Old Java Object. These should match the Json response in terms of structure and field names. We don’t have to create every single structure and field, we only create the needed ones, that we will be using in our app.

To organize the project’s structure, create a models package folder under your main -> java -> {app package folder} . We will create all the Dictionary Related Classes under this folder.

First we will create the DictionaryInfo Class

Then the DictionaryResult Class

After that, the LexicalEntry Class

Next create the Entry Class:

Then create the Sense Class

Now that we have the full object graph created, let’s create the Retrofit Api Interface. We will name it IDictionariesApi, and define one endpoint inside it to get the dictionary entries of a given word.

Notice above, we have a new annotation @Header, this is a Retrofit specific annotation which will allow you the pass the request headers to the targeting HTTP endpoint, where every argument represents a request header entry.

Next, let’s create our ApiManager Class which will be used to hold the singleton instance of our Retrofit service client with the base URL pointing to the Oxford Dictionaries API, https://od-api.oxforddictionaries.com/api/v1/ , and it will contain the method call to get the dictionary entries.

Don’t forget to extend the Application Class so that you can instantiate the singleton instance of the ApiManager upon the start of the application

And add the name attribute in the Application section of AndroidManifest.xml file to become the .MainApplication

If you don’t wish to use the @Header annotation of the Retrofit library to pass the needed request headers, you can use the interceptor methodology. It is very simple to implement the intercepter, you only need to create an OkHttp instance and add a new Interceptor class in it, and then inside the intercept method, you will inject the headers you want within the request chain and then proceed the request.

In the ApiManager constructor, do the following:

And then remove the extra paramters we added in the getDictionaryEntries method in ApiManager and in the Retrofit Interface.

Using the interceptor methodology is a better approach to inject request headers into your HTTP requests, this will be really useful when your app grows with more endpoints to the same APIs, where you don’t have to pass the request headers each time, the request headers will already be injected upon the initialization of the app.

Now we will jump up to the UI layer of the app, and we will start preparing the layout of our dictionary app.

In the activity_main.xml file, we want to have few widgets: an EditText for the user to input the search word, a Button to do the API call and a ListView to display the results. We will also add a progress bar spinner to show the user while the API call is taking place.

And to populate the ListView, we want to have a custom layout that will display the lexical category of the entry such as noun, verb …etc. , and the definition of the word. We will style it in a way that will be appealing to user. As you already know, there are numerous words in English that can have more than 1 definition per its lexical category.

So, let’s create a new xml layout file and name it dictionary_entry.xml

Now we have both our layouts ready to be inflated from the code.

Let’s first go and create the adapter. It will extend the BaseAdapter Class, and it will follow the ViewHolder pattern to effectively inflate/bind the ListView.

ViewHolder pattern is an effective way to display items in list, this is particularly effective when the list is long to have a scroll. This means that the operation findViewById will not be called every time the layout is inflated (in the case of scrolling) , but a ViewHolder Class will store direct reference to the UI Elements and then this ViewHolder will be stored in a tag of the view after inflating it. So the next render of the List Item’s row will get the references from the tag and populate the needed values, it will not call the findViewById again.

If you use a RecyclerView, it is a must that you follow the ViewHolder pattern, as it is built on it. I could simply used the RecyclerView in this tutorial, as previous tutorials, but I wanted to show how we can use the ListView and how can we apply the ViewHolder pattern in it.

If you want to read more about ViewHolder pattern, check this link.

Now back to our app, create a class with name DictionaryAdapter

Finally, let’s go to our MainActivity class, and glue all the above.

In short, the above code will create the DictionaryAdapter with initial values, and it will prepare the needed UI elements. Clicking the search button, will trigger a call to the Dictionary Entries Endpoint of the Oxford Dictionaries API , using the app_id and app_key that we defined in the ApiManager class. and then if the call happens and returns 200, we will populate the list view with the response after mapping it (automatically) with the DictionaryInfo object.

If the response contained multiple lexical categories, then these will displayed on top of each other , displaying a scrollbar if the output extends the viewport of the screen.

Now, let’s run our app and see the results.

          

 

Conclusion

This was the 3rd and last tutorial in our series of implementing Retrofit in Android. In this tutorial we covered a very important and commonly used functionality which is passing request headers to API calls, where we discussed the 2 ways to add the request headers: Retrofit Annotations and the OkHttp Interceptor Class. We discussed and wrote an app that will connect to the popular Oxford Dictionaries API.

Please let me know if you liked this tutorial and the previous 2 tutorials. and don’t forget to share these tutorials on your social network to help spread the word for all learners.

Bonus

Allow me to share with you this wonderful piano sonata. This is one of my favourite masterpieces composed by the music Virtuoso, W. A. Mozart.

It is piano sonata No 14 in C minor (K457), includes 3 movements.

Leave a Reply