Skip to main content

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:


Comments

Popular posts from this blog

Google re-branded the support Android libraries to AndroidX

It is important to note, you cannot mix AppCompat and Jetpack in the same project. You must convert everything to use Jetpack if you want to upgrade. The support library artifacts are being deprecated and all future development is going into AndroidX , so there's no avoiding this migration. Alan Viverette sums this up nicely: “There won’t be a 29.0.0, so Android Q APIs will only be in AndroidX” The stable release of 28.0.0 will be the final feature release packaged as android.support . All subsequent feature releases will only be made available as androidx-packaged artifacts. Below tips will give you a clearer transition path. The current version of AppCompat (v28.x) is exactly the same as AndroidX (v1.x). In fact, the AppCompat libraries are machine generated by changing maven coordinates and package names of the AndroidX codebase. For example, android.support.v7.app.AppCompatActivity is now androidx.appcompat.app.AppCompatActivity For a complete listi...

Android Studio Release Updates

JetBrains's  Android Studio’s 10 year anniversary      I remember the major change which has taken place since I started learning android is Android Studio migration from Eclipse. Android Studio’s 10 year anniversary. Watch official youtube : Android Studio’s 10th birthday: our favorite moments!      In December 2014 , Google launched Android Studio, Google's official Integrated Development Environment (IDE) based on IntelliJ and it discontinued the Android Developer Tools (ADT) plugin for Eclipse, which means it’s time to leave eclipse behind.        Fortunately, we had simple solution to migrate, Android Studio offered a better experience for Android developers and its migration functionality does most of the work for you.      Open Android Studio and click on the option:  Import project (Eclipse ADT, Gradle, etc) Before Android studio      1. users had to go download a JDK, then download Eclipse...

Firebase with android: An Overview of Products and Usage

Introduction: In the evolving landscape of mobile application development, understanding user behaviour, managing user identity, and delivering personalised communication are critical components of a successful digital product. Google provides a suite of powerful tools through Firebase and Google Analytics that help developers build, improve, and grow their applications efficiently. This article explores Google Analytics , Firebase Authentication , Firebase Cloud Messaging (push notifications), and other core Firebase products , along with their practical uses. Google Analytics Google Analytics for Firebase is a free app measurement solution that provides insights on app usage and user engagement. Unlike traditional Google Analytics, this version is tightly integrated with Firebase services, making it highly useful for mobile and cross-platform apps. Key Features: Event tracking : Automatically or manually track user actions like screen views, button taps, purchases, etc. User segm...