Kotlin HTTP Example (Using Fuel HTTP)

Introduction

Since the announcement of Kotlin at Google I/O 2017, we have seen a series of tutorials in Kotlin. If you are new to Kotlin, you can learn Kotlin from our previous articles.

We covered the basics of Kotlin and Hello World functions, how to use ListView, RecyclerView in Kotlin and how to implement SQLite storage in Kotlin with CRUD operations.

In this article, we will learn how to make a server call (i.e. HTTP Connection) from a Kotlin-powered application to web services.

Coding Part

I have divided the coding part into 3 steps as shown in the following.

  • Creating a new project.
  • Setting up the project with Fuel HTTP.
  • Implementing the Fuel HTTP Service Call.

Let’s start coding for Fuel HTTP.

Step 1 - Creating a new project

  1. Open Android Studio and Select "Create a new project".
  2. Name the project as per your wish and tick the Kotlin checkbox support.
  3. Then Select your Activity type (For Example: Navigation Drawer Activity, Empty Activity, etc.).

    Kotlin

  4. Then, click Finish button to create a new project in Android Studio.

Step 2 - Setting up the project

Now, we will be setting up the project for Fuel HTTP.

  1. Open your app level gradle file and add the following line.
    1. implementation 'com.github.kittinunf.fuel:fuel-android:1.6.0'  
  1. If you are using Android Studio Version below 3.0, then add the following (Optional Step).
    1. compile 'com.github.kittinunf.fuel:fuel-android:1.6.0'  
  1. Then Click “Sync Now” to download the library and add to the project.

After this, you are ready to implement HTTP Service Call from your Application.

Step 3 - Fuel HTTP implementation

Now, we will be setting up the project for Fuel HTTP.

  1. Open your AndroidManifest.xml and Add permission to access internet.
    1. <uses-permission android:name="android.permission.INTERNET"/>  
  1. Open your activity_main.xml file and create the User Interface as you want or paste the following code.
    1. <?xml version="1.0" encoding="utf-8"?>  
    2. <ScrollView xmlns:android="http://schemas.android.com/apk/res/android"  
    3.     xmlns:tools="http://schemas.android.com/tools"  
    4.     android:layout_width="match_parent"  
    5.     android:layout_height="match_parent"  
    6.     tools:context="com.androidmads.kotlinfuelhttpsample.MainActivity">  
    7.   
    8.     <LinearLayout  
    9.         android:layout_width="match_parent"  
    10.         android:layout_height="wrap_content"  
    11.         android:gravity="center"  
    12.         android:orientation="vertical">  
    13.   
    14.         <TextView  
    15.             android:layout_width="match_parent"  
    16.             android:layout_height="wrap_content"  
    17.             android:padding="10dp"  
    18.             android:text="GET Request's Response"  
    19.             android:textColor="#000000" />  
    20.   
    21.         <TextView  
    22.             android:id="@+id/tvGetResponse"  
    23.             android:layout_width="match_parent"  
    24.             android:layout_height="wrap_content"  
    25.             android:layout_marginLeft="10dp"  
    26.             android:layout_marginRight="10dp"  
    27.             android:background="#e1e1e1"  
    28.             android:padding="10dp"  
    29.             android:text="" />  
    30.   
    31.         <Button  
    32.             android:layout_width="match_parent"  
    33.             android:layout_height="wrap_content"  
    34.             android:layout_margin="10dp"  
    35.             android:background="@color/colorPrimary"  
    36.             android:onClick="httpGetJson"  
    37.             android:text="GET RESPONSE"  
    38.             android:textColor="#ffffff" />  
    39.   
    40.         <TextView  
    41.             android:layout_width="match_parent"  
    42.             android:layout_height="wrap_content"  
    43.             android:padding="10dp"  
    44.             android:text="POST Request's Response"  
    45.             android:textColor="#000000" />  
    46.   
    47.         <TextView  
    48.             android:id="@+id/tvPostResponse"  
    49.             android:layout_width="match_parent"  
    50.             android:layout_height="wrap_content"  
    51.             android:layout_marginLeft="10dp"  
    52.             android:layout_marginRight="10dp"  
    53.             android:background="#e1e1e1"  
    54.             android:padding="10dp"  
    55.             android:text="" />  
    56.   
    57.         <Button  
    58.             android:layout_width="match_parent"  
    59.             android:layout_height="wrap_content"  
    60.             android:layout_margin="10dp"  
    61.             android:background="@color/colorPrimary"  
    62.             android:onClick="httpPostJson"  
    63.             android:text="POST RESPONSE"  
    64.             android:textColor="#ffffff" />  
    65.   
    66.     </LinearLayout>  
    67. </ScrollView>  

Layout Preview

Kotlin
  1. Then Open your Activity file and here I am opening a Java file.
  2. Initialize the fuel library by the following code
    1. FuelManager.instance.basePath = "http://demosmushtaq.16mb.com";  

Here, you must specify the base address of your service. It will start or initialize the library.

GET REQUEST

We will use “Fuel.get()” to make server call with Get method. The following code shows how to implement this.

  1. Fuel.get("<Service Link without base path>").responseJson { request, response, result ->  
  2.     Log.v(“response”, result.get().content)  
  3. }  

POST REQUEST

We will use “Fuel.post()” to make server call with Post method. The following code shows how to implement this.

  1. Fuel.post("<Service Link without base path>",  
  2.                   listOf("<key>" to "<value>")).responseJson { request, response, result ->  
  3.     Log.v(“response”, result.get().content)  
  4. }  

You can pass the data to service using “listOf” method. It is an optional value. You can also access the without the parameters to be passed

You can get the response as string or json by specifying the response type “responseString” or “responseJson” respectively.

You can get response from the result using “result.get().content” as mentioned in the code above.

Full Code of MainActivity

You can find the full code implementation of MainActivty.kt in the following.

  1. class MainActivity : AppCompatActivity() {  
  2.   
  3.     var tvGetResponse: TextView? = null  
  4.     var tvPostResponse: TextView? = null  
  5.     var progress: ProgressDialog? = null  
  6.   
  7.     override fun onCreate(savedInstanceState: Bundle?) {  
  8.         super.onCreate(savedInstanceState)  
  9.         setContentView(R.layout.activity_main)  
  10.         initViewsAndWidgets()  
  11.         FuelManager.instance.basePath = "http://demosmushtaq.16mb.com";  
  12.     }  
  13.   
  14.     private fun initViewsAndWidgets() {  
  15.         tvGetResponse = findViewById(R.id.tvGetResponse)  
  16.         tvPostResponse = findViewById(R.id.tvPostResponse)  
  17.         progress = ProgressDialog(applicationContext)  
  18.         progress!!.setTitle("Kotlin Fuel Http Sample")  
  19.         progress!!.setMessage("Loading...")  
  20.     }  
  21.   
  22.     fun httpGetJson(view: View) {  
  23.         try {  
  24.             progress!!.show()  
  25.             Fuel.get("api/get_sample.php").responseJson { request, response, result ->  
  26.                 tvGetResponse!!.text = result.get().content  
  27.             }  
  28.         } catch (e: Exception) {  
  29.             tvPostResponse!!.text = e.message  
  30.         } finally {  
  31.             progress!!.dismiss()  
  32.         }  
  33.     }  
  34.   
  35.     fun httpPostJson(view: View) {  
  36.         try {  
  37.             progress!!.show()  
  38.             Fuel.post("api/post_sample.php", listOf("version_index" to "1")).responseJson { request, response, result ->  
  39.                 tvPostResponse!!.text = result.get().content  
  40.             }  
  41.         } catch (e: Exception) {  
  42.             tvPostResponse!!.text = e.message  
  43.         } finally {  
  44.             progress!!.dismiss()  
  45.         }  
  46.     }  
  47. }  

Download Code

You can download sample code from the following GitHub link.