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 Beginners Guide

                                                                                                               Android Operation System: Android is an operating system based on Linux with a Java programming interface. It provides tools, e.g. a compiler, debugger and a device emulator as well as its own Java Virtual machine (Dalvik Virtual Machine - DVM). Android is created by the Open Handset Alliance which is lead by Google. Android uses a special virtual machine, e.g. the Dalvik Virtual Machine. Dalvik uses special bytecode. Therefore you cannot run standard Java bytecode on Android. Android provides a tool "dx" which allows to convert Java Class files into "dex" (Dalvik Executable) files. Android ...

Kotlin and Android

Kotlin is now an official language on Android. It's expressive, concise, and powerful. Best of all, it's interoperable with our existing Android languages and runtime. To use Kotlin in Android Studio prior to version 3.0 you have to manually install the Kotlin plugin. To do so, start Android Studio and open Plugins from the Configure menu . In the opened dialog, search for Kotlin , select the corresponding plugin and press Install . Kotlin for Android Development: Kotlin is a great fit for developing Android applications, bringing all of the advantages of a modern language to the Android platform without introducing any new restrictions. Compatibility: Kotlin is fully compatible with JDK 6, ensuring that Kotlin applications can run on older Android devices with no issues. The Kotlin tooling is fully supported in Android Studio and compatible with the Android build system. Performance: A Kotlin application runs as fast as an equivalent Java one, thanks to ver...