Using Retrofit REST client
Retrofit
What is RetrofitRetrofit is a REST Client for Android and Java by Square. It makes it relatively easy to retrieve and upload JSON (or other structured data) via a REST based webservice. In Retrofit you configure which converter is used for the data serialization. Typically for JSON you use GSon, but you can add custom converters to process XML or other protocols. Retrofit uses the OkHttp library for HTTP requests.
Compare Retrofit with Volley
Easy to Configure
Retrofit is dead-simple to use. It essentially lets you treat API calls as simple Java method calls, so you only define which URLs to hit and the types of the request/response parameters as Java classes
The entire network call + JSON/XML parsing is completely handled by it (with help from Gson for JSON parsing), along with support for arbitrary formats with pluggable serialization / (d)serialization. Documentation is great and the community is huge. I'll just paste some code here so you get a feel for what I'm talking about.
Image loading
Retrofit does not come with support for loading images from the network by itself. Another small library called Picasso is recommended for this. I really don't consider this a drawback because (a) Picasso is just as easy to use as Retrofit, and, (b) it avoids over-burdening the core library and bloating your APK if you don't need image loading features -- indeed this might be considered an advantage if you're looking for a smaller library over ease-of-use for images.
Performance and caching
Both libraries use thread pools and execute multiple requests in parallel, and both support the venerable OkHttp library.
Retrofit: caching should "just work" if your server sets the correct cache control headers. If not, or if you're trying to do something unusual, you may be out of luck. The only lever you can turn here is your HTTP client layer (OkHttp, HttpUrlConnection, etc), as in this example.
Volley definitely has a more elaborate and flexible caching mechanism. Glide leverages it to great effect for caching bitmaps.
Request prioritization, cancellation and retrying
Retrofit: does not support setting priority, although there are hacks available; supports cancellation since v2 (which is in late beta now); supports manual request retries.
Volley: supports prioritization with a little extra code; supports cancellation and customizable retry with exponential backoff out-of-the-box.
POST requests + multipart uploads
Retrofit has full support for POST requests and multipart file uploads, with a sweet API to boot.
Volley supports POST requests but you'll have to convert your Java objects to JSONObjects yourself (e.g., with Gson). Also supports multipart requests but you need to add these additional classes or equivalent. The experience is not as polished as with Retrofit, but probably a bit more flexible as a result.
Extensibility
Retrofit has a well-designed, intuitive API with a small number of extension points for common use-cases, e.g., for (de)serialization and request threading. Jake Wharton discusses Retrofit 2's extension points in his great talk from Droidcon NYC 2015.
Volley on the other hand is very open to extension and even relies on that fact for common features like request priority, setting up a global long-lived RequestQueue, and bitmap caching. The success of Glide is proof of Volley's great extensibility.
Dynamic URLs
Retrofit supports dynamic URLs since v2. By "dynamic" I mean the URL is not known until runtime, as is the case with pagination in Github's API, which sends previous/next page links in the response headers and the URLs can be unguessable.
Volley obviously supports dynamic URLs, as we saw in the very first example above, the URL being the second parameter in the StringRequest constructor.
Let's tale a look, How we can work with Retrofit
Basically we need the below three classes to work with retrofit
- Model class which is used to map the JSON data to
- Interfaces which defines the possible HTTP operations
- Retrofit.Builder class - Instance which uses the interface and the Builder API which allows defining the URL end point for the HTTP operation.
Every method of an interface represents one possible API call.
It must have a HTTP annotation (GET, POST, etc.) to specify the request type and the relative URL. The return value wraps the response in a Call object with the type of the expected result.
@GET("users")
Call<List<User>> getUsers()
You can use replacement blocks and query parameters to adjust the URL.
A replacement block is added to the relative URL with {}. With the help of the @Path annotation on the method parameter, the value of that parameter is bound to the specific replacement block.
@GET("users/{name}/commits")
Call<List<Commit>> getCommitsByName(@Path("name") String name)
Query parameters are added with the @Query annotation on a method parameter. They are automatically added at the end of the URL.
@GET("users")
Call<User> getUserById(@Query("id") Integer id)
The @Body annotation on a method parameter tells Retrofit to use the object as the request body for the call.
@POST("users")
Call<User> postUser(@Body User user)
Methods can also be declared to send form-encoded and multipart data.
Form-encoded data is sent when @FormUrlEncoded is present on the method. Each key-value pair is annotated with @Field containing 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);
Multipart requests are used when @Multipart is present on the method. Parts are declared using the @Part annotation.
@Multipart
@PUT("user/photo")
Call<User> updateUser(@Part("photo") RequestBody photo, @Part("description") RequestBody description);
Multipart use one of Retrofit's converters or they can implement RequestBody to handle their own serialization.
You can set static headers for a method using the @Headers annotation.
@Headers("Cache-Control: max-age=640000")
@GET("widget/list")
Call<List<Widget>> widgetList();
@Headers({
"Accept: application/vnd.github.v3.full+json",
"User-Agent: Retrofit-Sample-App"
})
@GET("users/{username}")
Call<User> getUser(@Path("username") String username);
Note that headers do not overwrite each other. All headers with the same name will be included in the request.
A request Header can be updated dynamically using the @Header annotation. A corresponding parameter must be provided to the @Header. If the value is null, the header will be omitted. Otherwise, toString will be called on the value, and the result used.
@GET("user")
Call<User> getUser(@Header("Authorization") String authorization)
Converters can be added to support other types. Six sibling modules adapt popular serialization libraries for your convenience.
- 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
Example Code for Convert in desire format
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.example.com")
.addConverterFactory(GsonConverterFactory.create())
.build();
MySampleService service = retrofit.create(MySampleService.class);
I hope you enjoyed this help full Blog.
Comments
Post a Comment