Introduction

Retrofit is a type safe rest client for android and java development by square.it uses OkHttp library for Http request and it consider best tool for performing network request in Android application. Retrofit library is different from other network libraries because it gives us an easy to use platform through which we don’t need to parse JSON responses as they’re done by library itself. It used GSON library within the background to parser the response data. What we’d like to try to do is define a POJO (Plain Old Java Object) to parse the response.

Uses of retrofit

Retrofit is employed to perform the subsequent tasks:

  •  Retrofit manages the the way to receive, send, and build HTTP requests and responses.
  •  Retrofit can alternates IP addresses if there’s a connection to an internet service failure.
  •  Retrofit caches responses to avoid sending requests again.
  •  Retrofit can pools connections to cut back latency.
  • Retrofit can resolves issues before sending a blunder and crashing the app.

Advantages of retrofit

  • It is very fast as compare to other network library.
  • It has ability to enables direct communication with the web service.
  • It is easy to use and understand.
  • It has capability to request cancellation.
  • It can do post requests and multipart uploads.
  • It can do both synchronous and asynchronous network requests.
  • it supports dynamic URLs.
  • it supports convertors.

Disadvantages of retrofit

  • Retrofit unable to support image loading. It needs other libraries such as Glide and Picasso.
  • Retrofit unable to support setting priorities.

Performance time required for Android AsyncTask, Volley and Retrofit (in milliseconds, lower value is better):

AsyncTaskVolleyRetrofit
one(1) discussion: 941 ms
one(1) discussion: 560 ms
one(1) discussion: 312 ms
Seven(7) discussions: 4539 ms
Seven(7) discussions: 2202 ms
Seven(7) discussions: 889 ms
Twenty Five(25) discussions: 13957 ms
Twenty Five(25) discussions: 4275 ms
Twenty Five(25) discussions: 1059 ms

Creating the Retrofit instance

we need to use the Retrofit builder class to create retrofit instance and specify the base URL for the service to send network request.

/ Creating retrofit instance
public static final String BASE_URL = "http://api.myapi.com/";
Retrofit retrofit = new Retrofit.Builder()
    .baseUrl(BASE_URL)
    .addConverterFactory(GsonConverterFactory.create())
    .build();

Keep remember that we need to specify a factory which help us for deserializing the response using the Gson library. 

Gson gson = new GsonBuilder()
        .setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ")
        .create();

Retrofit retrofit = new Retrofit.Builder()
    .baseUrl(BASE_URL)
    .addConverterFactory(GsonConverterFactory.create(gson))
    .build();

Define the Endpoints

To define endpoints we need an interface and use some special retrofit annotations to make request method. These annotations helps to encode details about the parameters. The return value is often a parameterized Call object like Call. If you do not need any type-specific response, you’ll be able to specify return value as simply Call.

For Example:

public interface ApiEndpointInterface {

    @GET("students/{studentsname}")
    Call<Students> getUser(@Path("studentsrname") String studentsname);

    @GET("group/{id}/students")
    Call<List<Students>> groupList(@Path("id") int groupId, @Query("sort") String sort);

    @POST("students/new")
    Call<Students> createUser(@Body Students Students);
}

Annotation Description

  • @Path variable substitution for the API endpoint (i.e. username are going to be swapped for within the URL endpoint).
  • @Query specifies the query key name with the worth of the annotated parameter.
  • @Body used for the POST call .
  • @Header specifies the header with the worth of the annotated parameter.

Changing the base URL

Normally, While instantiated a Retrofit instance we define the base URL. Retrofit 2 give permission to override the base URL specified by changing it in the annotation 

@POST("https://api.github.com/api/v3")
Here you can modify the base URL with the help of relative paths (and not the fully qualified URL) as discussed in this blog article.

Adding headers

Keep remember that there is a @Headers and @Header annotation and Headers can be used to provide pre-defined ones:

@Headers({"Cache-Control: max-age=640000", "User-Agent: My-App-Name"})
@GET("/some/endpoint")
We can also add headers as a parameter to the url endpoint:

Form data

If we want to use form-encoded data then we can use the FormUrlEncoded annotation. The @Field annotation will help you what payload will be submitted as form data.

@FormUrlEncoded
@POST("/some/endpoint")
Observable<SomeResponse> someEndpoint(@Field("code") String code);

Multipart forms

If you are working with files and upload images in retrofit then you should go with Multipart forms. For this you just need to annotate endpoint with @Multipart, and label at least one parameter with @Part.

@Multipart
@POST("some/endpoint")
Call<Response> uploadImage(@Part("description") String description, @Part("image") RequestBody image)

Suppose we have a reference to the file, we have to create a RequestBody object:-

MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");
file = new File("/storage/emulated/0/Pictures/MyApp/test.png");
RequestBody requestBody = RequestBody.create(MEDIA_TYPE_PNG, file);
Call<Response> call = apiService.uploadImage("test", requestBody);

If you are working to send a unique filename for your multipart upload, here is an issue in Retrofit 2. For this you have to create a multi-part RequestBody as per OkHttp pattern given below and pass it along as one of the @Part annotated parameters:-

RequestBody requestBody = new MultipartBody.Builder()
        .setType(MultipartBody.FORM)
        .addFormDataPart("title", "User name")
        .addFormDataPart("image", "user_image.png",
            RequestBody.create(MEDIA_TYPE_PNG, new File("website/static/logo-   square.png")))
        .build();

Form URL encoding

If you are working with to POST form-encoded name/value pairs, you should go with the @FormUrlEncoded and @FieldMap annotations:-

@FormUrlEncoded
@POST("some/endpoint")
Call<SomeResponse> someEndpoint(@FieldMap Map<String, String> names);

Parsing JSON data

As we know that Retrofit 2 use the converter library which is use to handle the deserialization of information from a Java object. If you will annotate the parameter with a @Body parameter, this work are going to be done automatically. If you’re using the Gson library as an example, any field belonging to the category are serialized for you. you’ll be able to change this name using the @SerializedName decorator.

public class Student {

  @SerializedName("id")
  int mId;

  @SerializedName("name")
  String mName;

  public Student(int id, String name ) {
    this.mId = id;
    this.mName = name;
  }
}

And endpointmust be look like:

@POST("/students/new")
Call<Student> createStudent(@Body Student Student);

And API call as follows:

Student student = new Student(123, "Codinglance");
Call<Student> call = apiService.createstudent(Student);
call.enqueue(new Callback<Student>() {
  @Override
  public void onResponse(Call<Student> call, Response<Student> response) {

  }

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

  }
  
The result would be:

{"name":"Codinglance","id":123}

Difference between Retrofit and Volley

RetrofitVolley
Retrofit can parse many other type of data Response automatically like Boolean, Integer, String, Object etc.Volley has different type of request for different type of Response like String request, Json object request,Json array request,Image request.
Retrofit does not support caching mechanism Volley support caching mechanism.
Retrofit does not support any retry mechanism.Volley has retry mechanism using the set Retry policy method.
Retrofit has full support of post requests.
Volley also support both but for post request we have to convert our java object to json object also for multipart upload we have to do some extra code and use some extra classes.

You may also like...

0 Comments

No Comment.