Home / Server Side / Retrofit / Retrofit Android Library Tutorial – Library #6
retrofit_cover

Retrofit Android Library Tutorial – Library #6

This is library #6 in this series 100 Library in Android , in the previous article we had Picasso Android Library Tutorial . In this tutorial we are having the Retrofit Android Library Tutorial which is a type-safe HTTP client for Android and Java by Square. By using Retrofit in Android we can seamlessly capture JSON responses from a web API. It is different from other libraries because Retrofit gives us an easy way to use since it uses the GSON library in background to parse the responses. All we need to do is define a POJO (Plain Old Java Object) to do all the parsing. In this Retrofit Android Library Tutorial, we will discuss the basic scenarios where it can be used.

Our Application:

Our application will use Retrofit Library to make a sample application has a single button “London Current Weather”. Once the user is going to click on this button, London current weather data are appeared on defined TextViews  by integrating with REST web API from OpenWeatherMap.

Comparison of AsyncHttp ,Volley and Retrofit which this is showing how retrofit is beating other libraries

Retrofit Android Library Tutorial

Converters:

In the past, Retrofit relied on the GSON library to serialize and deserialize JSON data. Retrofit 2 now supports many different parsers for processing network response data, including Moshi, a library build by Square for efficient JSON parsing. However, there are a few limitations, so if you are not sure which one to choose, use the Gson converter for now.

ConverterLibrary
Gsoncom.squareup.retrofit2:converter-gson:2.0.2
Jacksoncom.squareup.retrofit2:converter-jackson:2.0.2
Moshicom.squareup.retrofit2:converter-moshi:2.0.2
Protobufcom.squareup.retrofit2:converter-protobuf:2.0.2
Wirecom.squareup.retrofit2:converter-wire:2.0.2
Simple XMLcom.squareup.retrofit2:converter-simplexml:2.0.2

Main Steps:

  1. First of all, you have to create a free account on OpenWeatherMap to get a free Application ID to be able to access OpenWeatherMap APIs,the creating account steps are very sample.
  2. Create an Android Application.
  3. Add permission to your Manifest.xml and build.gradle file.
  4. Start to access OpenWeatherMap APIs to get London current weather data.

1. Setup

  • Retrofit Library dependency and its Gson converter library dependency should be added in the build.gradle of Retrofit Example Application:
  • Internet permission should be added in the Manifest.xml file.

2. Creating a Retrofit Request

  • To send out network requests to an API, you need to use the Retrofit.Builder class and specify the base URL for the service.
  • Note also that you need to specify a factory for deserializing the response using the GSON library. If you wish to pass in a custom Gson parser instance, it can be specified too:

3. Defining The Endpoints

  • With Retrofit 2, endpoints are defined inside of an interface using special retrofit annotations to encode details about the parameters and request method. In addition, the return value is always a parameterized Call<T> object such as Call<WeatherDataBean>. If you do not need any type-specific response, you can specify return value as simply Call<ResponseBody>.
  • Notice that each endpoint specifies an annotation of the HTTP method (GET, POST, etc.) and method that will be used to dispatch the network call. Note that the parameters of this method can also have special annotations:
AnnotationDescription
@Pathvariable substitution for the API endpoint (i.e. username will be swapped for {username} in the URL endpoint).
@Queryspecifies the query key name with the value of the annotated parameter.
@Bodypayload for the POST call (serialized from a Java object to a JSON string)
@Headerspecifies the header with the value of the annotated parameter

4. Changing the base URL

  • Normally, the base URL is defined when you instantiated an Retrofit instance. Retrofit 2 allows you to override the base URL specified by changing it in the annotation

5. Adding Headers

  • Notice that there is a @Headers and @Header annotation. The Headers can be used to provide predefined ones:
  • You can also add headers as a parameter to the endpoint:

6. Uploading images or files

  • If you need to upload images or files, you need to send by using Multipart forms. You will to mark the endpoint with @Multipart, and label at least one parameter with @Part.
  • Assuming you have a reference to the file, you can create a RequestBody object:
  • If you need to specify a unique filename for your multipart upload. Alternatively, you can create a multi-part RequestBody according to this OkHttp recipe guide and pass it along as one of the @Part annotated parameters:

7. Request from URL Encoding

  • If you want to make a Retrofit request form-encoded name/value pairs, you can use the @FormUrlEncoded and @FieldMap annotations:

8. POST or CREATE fields by JSON data

  • Retrofit 2 will use the converter library chosen to handle the deserialization of data from a Java object. If you annotate the parameter with a @Body  parameter, this work will be done automatically. If you are using the Gson library for instance, any field belonging to the class will be serialized for you. You can change this name using the @SerializedName decorator:
  • Our endpoint would look like the following:
  • You could invoke this API call as follows:

9. Accessing API Asynchronously or Synchronously

  • If you want to consume the API asynchronously, you call the service as follows:
  • If you want to consume the API synchronously, you call the service as follows:

10. Using Authentication Headers

  • Headers can be added to a request using an Interceptor. To send requests to an authenticated API, add headers to your requests using an interceptor as outlined below:

Creating Retrofit Example Project:

Retrofit Android Library Tutorial

  • In Android Studio, create a new activity, select Empty Activity and lets name RetrofitMainActivity.
  • For this Android Retrofit Example, we are showing responses in TextViews, hence a layout with the TextViews, Buttons and ProgressBar should be created, open activity_retrofit_main.xml and add this code:
  • Therefore we will make a POJO Class for the data we need, here we will need London current weather data. To parse the response properly you may need to define the WeatherDataBean class carefully. As it should have the same structure as JSON being returned in response. Although it is not required to define all the fields, if you don’t want to parse all of them.

JSON that we will parse from OpenWeatherMap APIs: 

You can convert your JSON object into POJO one through this websiteso go to this site, copy and paste this JSON above, select source type to be JSON and click generate.

Retrofit Android Library Tutorial

  • Next we will make a Java Interface class “GetWeatherApi” to access the web service. In GetWeatherApi interface you may notice that, two custom annotations have been used. The @GET annotation is used to define the relative HTTP URL path and method. While the @Query annotation is used to define the query string for URL.

GetWeatherApi.java Interface Class:

The above interface “GetWeatherApi” would be making a web API hit on the following URL:

  • Then we will go to implement GetWeatherApi interface function in onCreate() method of RetrofitMainActivity and start to handle synchronous and Asynchronous request calling.

RetrofitMainActivity.java Class

  • Finally The Retrofit Example Application after running should be as screenshots attached below:

Retrofit Android Library Tutorial

Main Screen with two buttons “London Current Weather Synchronously” and “London Current Weather Asynchronously”

Retrofit Android Library Tutorial

After pressing on “London Current Weather Synchronously”

Retrofit Android Library Tutorial

After pressing on “London Current Weather Asynchronously”

Retrofit Android Library Tutorial

Loading progress bar appears informing the user that your request is in progress

Retrofit Android Library Tutorial

 

Summary
Article Title
Retrofit Android Library Tutorial – Library #6
Description
Retrofit Android Library Tutorial, auto parse JSON using GSON, using Weather API example and GET, POST, PUT methods and convert JSON into POJO class
Author
Organization
Android Gifts

About Ahmed Adel

Ahmed Adel

Leave a Reply