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.
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 the “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 the 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. <LinearLayout
    8. android:layout_width="match_parent"
    9. android:layout_height="wrap_content"
    10. android:gravity="center"
    11. android:orientation="vertical">
    12. <TextView
    13. android:layout_width="match_parent"
    14. android:layout_height="wrap_content"
    15. android:padding="10dp"
    16. android:text="GET Request's Response"
    17. android:textColor="#000000" />
    18. <TextView
    19. android:id="@+id/tvGetResponse"
    20. android:layout_width="match_parent"
    21. android:layout_height="wrap_content"
    22. android:layout_marginLeft="10dp"
    23. android:layout_marginRight="10dp"
    24. android:background="#e1e1e1"
    25. android:padding="10dp"
    26. android:text="" />
    27. <Button
    28. android:layout_width="match_parent"
    29. android:layout_height="wrap_content"
    30. android:layout_margin="10dp"
    31. android:background="@color/colorPrimary"
    32. android:onClick="httpGetJson"
    33. android:text="GET RESPONSE"
    34. android:textColor="#ffffff" />
    35. <TextView
    36. android:layout_width="match_parent"
    37. android:layout_height="wrap_content"
    38. android:padding="10dp"
    39. android:text="POST Request's Response"
    40. android:textColor="#000000" />
    41. <TextView
    42. android:id="@+id/tvPostResponse"
    43. android:layout_width="match_parent"
    44. android:layout_height="wrap_content"
    45. android:layout_marginLeft="10dp"
    46. android:layout_marginRight="10dp"
    47. android:background="#e1e1e1"
    48. android:padding="10dp"
    49. android:text="" />
    50. <Button
    51. android:layout_width="match_parent"
    52. android:layout_height="wrap_content"
    53. android:layout_margin="10dp"
    54. android:background="@color/colorPrimary"
    55. android:onClick="httpPostJson"
    56. android:text="POST RESPONSE"
    57. android:textColor="#ffffff" />
    58. </LinearLayout>
    59. </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 a 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 a 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. var tvGetResponse: TextView? = null
  3. var tvPostResponse: TextView? = null
  4. var progress: ProgressDialog? = null
  5. override fun onCreate(savedInstanceState: Bundle?) {
  6. super.onCreate(savedInstanceState)
  7. setContentView(R.layout.activity_main)
  8. initViewsAndWidgets()
  9. FuelManager.instance.basePath = "http://demosmushtaq.16mb.com";
  10. }
  11. private fun initViewsAndWidgets() {
  12. tvGetResponse = findViewById(R.id.tvGetResponse)
  13. tvPostResponse = findViewById(R.id.tvPostResponse)
  14. progress = ProgressDialog(applicationContext)
  15. progress!!.setTitle("Kotlin Fuel Http Sample")
  16. progress!!.setMessage("Loading...")
  17. }
  18. fun httpGetJson(view: View) {
  19. try {
  20. progress!!.show()
  21. Fuel.get("api/get_sample.php").responseJson { request, response, result ->
  22. tvGetResponse!!.text = result.get().content
  23. }
  24. } catch (e: Exception) {
  25. tvPostResponse!!.text = e.message
  26. } finally {
  27. progress!!.dismiss()
  28. }
  29. }
  30. fun httpPostJson(view: View) {
  31. try {
  32. progress!!.show()
  33. Fuel.post("api/post_sample.php", listOf("version_index" to "1")).responseJson { request, response, result ->
  34. tvPostResponse!!.text = result.get().content
  35. }
  36. } catch (e: Exception) {
  37. tvPostResponse!!.text = e.message
  38. } finally {
  39. progress!!.dismiss()
  40. }
  41. }
  42. }

Download Code

You can download the sample code from the following GitHub link.