Implementing HTTP GET Requests with OkHttp in Android

Project Setup

To begin, add the OkHttp library dependency to your app's build.gradle file:

dependencies {
   implementation("com.squareup.okhttp3:okhttp:4.12.0")
}

Permissions and Configuration

Next, ensure your aplication has enternet access by adding the following permission to your AndroidManifest.xml:

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

For development purposes, especially when testing against local servers, you may need to allow cleartext traffic. Create a res/xml/network_security_config.xml file:

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
   <base-config cleartextTrafficPermitted="true" />
</network-security-config>

Then, reference this file in your AndroidManifest.xml:

android:networkSecurityConfig="@xml/network_security_config"

User Interface

Create a simple layout with a button to trigger the request and a TextView to display the response. Here's an example in res/layout/activity_main.xml:

<LinearLayout
   xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:orientation="vertical"
   android:padding="16dp">

   <Button
       android:id="@+id/button_fetch_data"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:text="Fetch Data" />

   <TextView
       android:id="@+id/text_response"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:layout_marginTop="16dp"
       android:text="Response will appear here..." />

</LinearLayout>

Executing the GET Request

In your activity, configure the OkHttpClient and implement the logic to send a GET request when the button is clicked. The following example uses Kotlin and View Binding.

package com.example.okhttpdemo

import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.example.okhttpdemo.databinding.ActivityMainBinding
import okhttp3.Call
import okhttp3.Callback
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import java.io.IOException

class OkHttpActivity : AppCompatActivity() {

   private lateinit var activityBinding: ActivityMainBinding
   private val httpClient = OkHttpClient()

   override fun onCreate(savedInstanceState: Bundle?) {
       super.onCreate(savedInstanceState)
       activityBinding = ActivityMainBinding.inflate(layoutInflater)
       setContentView(activityBinding.root)

       activityBinding.buttonFetchData.setOnClickListener {
           performGetRequest()
       }
   }

   private fun performGetRequest() {
       // Define the URL for the GET request
       val requestUrl = "https://api.example.com/data"

       // Build the request object
       val request = Request.Builder()
           .url(requestUrl)
           .build()

       // Enqueue the request for asynchronous execution
       httpClient.newCall(request).enqueue(object : Callback {
           override fun onFailure(call: Call, e: IOException) {
               // Handle failure, e.g., no network connection
               Log.e("OkHttp", "Request failed", e)
               runOnUiThread {
                   Toast.makeText(this@OkHttpActivity, "Request failed: ${e.message}", Toast.LENGTH_SHORT).show()
               }
           }

           override fun onResponse(call: Call, response: Response) {
               // Process the successful response
               response.use {
                   if (!response.isSuccessful) {
                       // Handle non-2xx responses
                       runOnUiThread {
                           Toast.makeText(this@OkHttpActivity, "Unexpected code: ${response.code}", Toast.LENGTH_SHORT).show()
                       }
                       return
                   }

                   // Read the response body
                   val responseBody = response.body?.string()
                   if (responseBody != null) {
                       // Update the UI on the main thread
                       runOnUiThread {
                           activityBinding.textResponse.text = responseBody
                       }
                   }
               }
           }
       })
   }
}

Tags: OkHttp Android networking

Posted on Fri, 05 Jun 2026 18:06:01 +0000 by spoons84