In this article, we will see how to make an HTTP request from an Android application to a server. This is usually done to fetch the data from the API servers.

Add permissions

As a first step, we should add the necessary permissions to make the HTTP request. INTERNET permission has to be added to the AndroidManifest.xml file. Open the Manifest file and add the following line inside the <manifest> tag.

<uses-permission android:name="android.permission.INTERNET" />

Add dependency implementations

We use the retrofit library to make the implementation simpler. It supports various request types like GET, POST, PUT, DELETE, etc., and allows customization through request headers, query parameters, and request bodies.

Add the Retrofit dependency to your app-level build.gradle file:

implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'

Create API interface

Create an interface that describes the API endpoints and their corresponding HTTP methods.

For example, let’s create a simple interface that fetches data from a public API.

interface ApiService {
    @GET("posts")
    fun getPosts(): Call<List<Post>>
}

@GET("posts") is an annotation provided by Retrofit which specifies the HTTP method for the API request. In this case, @GET indicates that the HTTP method is a GET request. The string argument "posts" represents the relative URL for the API endpoint. This relative URL is joined with the BASE_URL and the complete URL will be formed later while making the request.

Create Retrofit instance

Now, we need to create a Retrofit instance with the required configuration, including the base URL of the API.

The best way is to do it within a singleton class to ensure a single instance throughout the app.

object RetrofitClient {
    private const val BASE_URL = "https://api.example.com/"
    
    val instance: ApiService by lazy {
        val retrofit = Retrofit.Builder()
            .baseUrl(BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .build()
            
        retrofit.create(ApiService::class.java)
    }
}

Make the HTTP request

To make the HTTP request, call the corresponding method from the API interface which we created earlier.

For example, to fetch the list of posts, we use the <strong>getPosts()</strong> API which is defined in the above API service interface.

val apiService = RetrofitClient.instance

apiService.getPosts().enqueue(object : Callback<List<Post>> {
    override fun onResponse(call: Call<List<Post>>, response: Response<List<Post>>) {
        if (response.isSuccessful) {
            val posts = response.body()
            // Process the data received from the server
        } else {
            // Handle the unsuccessful response (3xx, 4xx, 5xx)
        }
    }

    override fun onFailure(call: Call<List<Post>>, t: Throwable) {
        // Handle the HTTP failure
    }
})

In the above onResponse() method, we handle the response based on the status code received from the server. If the response code is between 200 – 299 then it is considered a successful response and get the response data received from the server using response.body().

Categorized in:

Tagged in:

,