Retrofit in Android

Type-safe HTTP client for Android and Java by Square, Inc.

  • Retrofit is a REST Client for Android and Java by Square.
  • This library is easy learn and has more features.
  • This is beginner friendly compared to other Networking libraries.
  • You can GET,POST,PUT,DELETE  ..etc using this library.
  • You can also use picasso for image loading.

3 classes

  • In Retrofit,we need to create 3 classes.
    POJO (Plain Old Java Object) or Model Class :– The json retrieved from the server is added to this class.
  • Interface :- Now we need to create an interface for managing url calls like GET,POST..etc.This is the service class.
  • RestAdapter Class :- This is RestClient Class. Gson is used in default for the retrofit.You can use setup your own converter

Adding Retrofit Library to Project
Gradle    : compile 'com.squareup.retrofit2:retrofit:2.0.2'     
MAVEN
<dependency>
<groupId>com.squareup.retrofit2</groupId>
<artifactId>retrofit</artifactId>
<version>2.0.2</version>
</dependency>

Also we can use JAR files.
Retrofit requires at minimum Java 7 or Android 2.3.

PROGUARD
If you are using Proguard in your project add the following lines to your configuration:
-dontwarn retrofit2.**
-keep class retrofit2.** { *; }
-keepattributes Signature
-keepattributes Exceptions

HTTP API
Retrofit turns your HTTP API into a Java interface.
public interface APIService {
 @GET("users/{user}/getAccessDetails")
 Call<List<AccessDetail>> listAccessDetail(@Path("user") String user);
}
Every method must have an HTTP annotation that provides the request method and relative URL
There are five built-in annotations:GET, POST, PUT, DELETE, and HEAD
The relative URL of the resource is specified in the annotation.

You can also specify query parameters in the URL. @GET("users/getAccessDetails?sort=desc")

URL MANIPULATION


  • A request URL can be updated dynamically using replacement blocks and parameters on the method.
  • A replacement block is an alphanumeric string surrounded by { and }.
  • A corresponding parameter must be annotated with @Path using the same string
@GET("group/{id}/users")
Call<List<User>> groupList(@Path("id") int groupId);
Query parameters can also be added.

@GET("group/{id}/users")
Call<List<User>> groupList(@Path("id") int groupId, @Query("sort") String sort);
For complex query parameter combinations a Map can be used.
@GET("group/{id}/users")
Call<List<User>> groupList(@Path("id") int groupId, @QueryMap Map<String, String> options);

REQUEST BODY

An object can be specified for use as an HTTP request body with the @Body annotation.
@POST("users/new")
Call<User> createUser(@Body User user);

The object will also be converted using a converter specified on the Retrofit instance.

FORM ENCODED AND MULTIPART

  • Methods can also be declared to send form-encoded and multipart data.
  • Form-encoded data is sent when @FormUrlEncoded
  • Each key-value pair is annotated with @Fieldcontaining the name and the object providing the value

@FormUrlEncoded
@POST("user/edit")
Call<User> updateUser(@Field("first_name") String first, @Field("last_name") String last);

HEADER MANIPULATION
You can set static headers for a method using the @Headers annotation.
@Headers({
"Accept: application/vnd.github.v3.full+json",
"User-Agent: Retrofit-Sample-App"
})

@GET("users/{username}")
Call<User> getUser(@Path("username") String username);
A request Header can be updated dynamically using the @Header annotation.
@GET("user")
Call<User> getUser(@Header("Authorization") String authorization)

SYNCHRONOUS VS. ASYNCHRONOUS

Call instances can be executed either synchronously or asynchronously. Each instance can only be used once, but callingclone() will create a new instance that can be used.

On Android, callbacks will be executed on the main thread. On the JVM, callbacks will happen on the same thread that executed the HTTP request.

CONVERTERS

  • Gson: com.squareup.retrofit2:converter-gson
  • Jackson: com.squareup.retrofit2:converter-jackson
  • Moshi: com.squareup.retrofit2:converter-moshi
  • Protobuf: com.squareup.retrofit2:converter-protobuf
  • Wire: com.squareup.retrofit2:converter-wire
  • Simple XML: com.squareup.retrofit2:converter-simplexml
  • Scalars (primitives, boxed, and String): com.squareup.retrofit2:converter-scalars
Here's an example of using the GsonConverterFactory
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.github.com")
.addConverterFactory(GsonConverterFactory.create())
.build();
GitHubService service = retrofit.create(GitHubService.class);

RX - Retrofit


Reference:


Popular posts from this blog

Step by step installation of Android 8.0 Oreo for Pixel and Nexus

Application icon tutorial for Android

Kannada News App for Android User