--

Tuesday, 10 April 2018

Kotlin - Chapter 2 - Developing Android Apps using Kotlin

Calling REST API in Kotlin


       I have implemented REST API call using HttpURLConnection & Retrofit API. We will create a connection between Android App and server at certain period then receive the data request from Android App to server.

Rest API and JsonObject Model :

      REST APIs is often used in mobile applications, social networking Web sites, mashup tools, and automated business processes. The REST style emphasizes that interactions between clients and services is enhanced by having a limited number of operations.

Using HttpURLConnection :

A URLConnection with support for HTTP-specific features.

Uses of this class follow a pattern:

  • Obtain a new HttpURLConnection by calling URL.openConnection() and casting the result to HttpURLConnection.
  • Prepare the request. The primary property of a request is its URI. Request headers may also include metadata such as credentials, preferred content types, and session cookies.
  • Optionally upload a request body. Instances must be configured with setDoOutput(true) if they include a request body. Transmit data by writing to the stream returned by URLConnection.getOutputStream().
  • Read the response. Response headers typically include metadata such as the response body's content type and length, modified dates and session cookies. The response body may be read from the stream returned by URLConnection.getInputStream(). If the response has no body, that method returns an empty stream.
  • Disconnect. Once the response body has been read, the HttpURLConnection should be closed by calling disconnect(). Disconnecting releases the resources held by a connection so they may be closed or reused.

Response Handling :

       HttpURLConnection will follow up to five HTTP redirects. It will follow redirects from one origin server to another. This implementation doesn't follow redirects from HTTPS to HTTP or vice versa.
If the HTTP response indicates that an error occurred, URLConnection.getInputStream() will throw an IOException. Use getErrorStream() to read the error response.



var - something that will vary with time. (Mutable )

val - for a value that won’t change. (Immutable - i.e. read-only)

Calling getUsers() function in doInBackground of inner class AsyncTask.



Note :
If you have to send GET/POST requests over HTTPS protocol, then all you need is to use javax.net.ssl.HttpsURLConnection instead of java.net.HttpURLConnection. Rest all the steps will be same as above, HttpsURLConnection will take care of SSL handshake and encryption.

Using Retrofit API

     Retrofit is type-safe HTTP client for Android and Java by Square, Inc. It is an open source library which simplifies HTTP communication by turning remote APIs into declarative, type-safe interfaces. It makes it relatively easy to retrieve and upload JSON (or other structured data) via a REST based web service. It automatically serializes the JSON response using a POJO which must be defined in advanced for the JSON Structure. 

     REST Client in our case is the Retrofit library that is used on the client side (Android) to make HTTP request to REST API, in our case, The USER API and also process the response. A REST API defines a set of functions which developers can perform requests and receive responses via HTTP protocol such as GET and POST. 

     We can also simply say that a RESTful API is an application program interface (API) that uses HTTP requests to GET, PUT, POST and DELETE data. We have to initialize Retrofit client by setting up baseUrl, addConverterFactory. 

By Query parameters can also be added to a method. creating interface for fetching list of users using gson library,

interface IUser{
@GET ("users")
fun getAllUsers() : Call<RetroUser>
}

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.




       A Retrofit class which generates an implementation of the UserService interface. The above sample code would be inside the Retrofit class and this is how it creates an instance of Retrofit and implements the getAllUsers() method that’s in the IUser Interface. By calling loadUsers() function in onCreate() override method.


Using simple service URL to fetch user details.
URL : https://reqres.in/api/users
The output would be,

Now save and run the App. You can download the full source code for this project on GitHub

Happy Coding !!!

No comments:

Post a Comment