android kotlin Create a HTTP Request without using any library

In this blog article, we will see how to create a HTTP Request without using any third party library.
In Android App Development , we usually depend on api on server with backend database and to create a connection with the server, we need to create HTTP Requests.
For API integration purpose we generally use popular networking libraries like Volley, Retrofit etc. in our project so that we can easily create the http requests for our use cases.
Of course, these libraries help us a lot to make our work easy and our HTTP Request calls faster.
But what if we don’t want to use any of these third party libraries.

Android - HttpURLConnection example

Let us see how to do this in Android and Kotlin:
Kotlin Code Approach:
  1. Create an suspend fun request with response type String
  2. Add suspendCancellableCoroutine that will resume on response of the HTTP API request and resumeWithException in case of any exception in API Call.
  3. There is no need to use the callback interface in case of the Kotlin Couroutines.
Kotlin Code
NetworkUtilityK.kt
package com.example.myapplication

import kotlinx.coroutines.suspendCancellableCoroutine
import org.json.JSONObject
import java.io.BufferedReader
import java.io.InputStreamReader
import java.io.Reader
import java.net.HttpURLConnection
import java.net.URL
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException

class NetworkUtilityK {
 
 companion object {

        suspend fun request(pageno: Int): String{
            return suspendCancellableCoroutine { continuation ->
                try {
                    val reader: BufferedReader
                    val url = URL("https://reqres.in/api/users?page=" + pageno + "&per_page=6")

                    with(url.openConnection() as HttpURLConnection) {
                        requestMethod = "GET"
                        reader = BufferedReader(InputStreamReader(inputStream) as Reader?)

                        val response = StringBuffer()
                        var inputLine = reader.readLine()
                        while (inputLine != null) {
                            response.append(inputLine)
                            inputLine = reader.readLine()
                        }
                        reader.close()

                        if (continuation.isActive) {
                            continuation.resume(response.toString())
                        }
                    }

                } catch (e: Exception) {
                    e.printStackTrace()
                    if (continuation.isActive) {
                        continuation.resumeWithException(e)
                    }
                }
            }
        }
    }
}

Calling the suspend fun request(pageno: Int)  inside Activity's onCreate() method :
class MainActivity : AppCompatActivity() {

    internal var page_count_dynamic = 1

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val binding: ActivityMainBinding =
            DataBindingUtil.setContentView(this, R.layout.activity_main)

        setSupportActionBar(toolbar)
        getSupportActionBar()?.setDisplayHomeAsUpEnabled(true);

        viewModel = ViewModelProviders.of(this)[MainViewModel::class.java]
        binding.mainVM = viewModel
        binding.setLifecycleOwner(this);

        CoroutineScope(Dispatchers.IO).launch{
            val rss = NetworkUtilityK.request(page_count_dynamic )
            withContext(Dispatchers.Main) {
                // call to UI thread and parse response
                val newlist=viewModel.parseJsonString(rss.toString())
                Log.e("ResSizedata","--list"+1+"::" + newlist.size+"::"+newlist)
            }
        }
}
}

Calling the suspend fun request(pageno: Int)  inside ViewModel :
class MainViewModel : ViewModel() {

    fun getData(page: Int) {
            viewModelScope.launch(Dispatchers.IO) {
                val rss = NetworkUtilityK.request(page)
                withContext(Dispatchers.Main) {
                    // call to UI thread
       
                    val newlist=parseJsonString(rss.toString())
                     
                }
        }
    }
 }

Android Code
NetworkUtility.java
package com.example.myapplication;

import android.os.AsyncTask;
import android.util.Log;

import org.json.JSONObject;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;

public class NetworkUtility {
    public static void getdata(APICallback apiCallback) {
        new MyHttpRequestTask(apiCallback).execute();
    }

    static class MyHttpRequestTask extends AsyncTask<String, Integer, String> {
        APICallback apiCallback;

        public MyHttpRequestTask(APICallback apiCallback) {
            this.apiCallback = apiCallback;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            this.apiCallback.onSucess(s);
        }

        @Override
        protected String doInBackground(String... params) {
            BufferedReader reader;
            String res = null;
            try {
                URL url = new URL("https://reqres.in/api/users?page=" + pageno + "&per_page=6");
                HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                // setting the  Request Method Type
                httpURLConnection.setRequestMethod("GET");

                try {
                    reader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
                    StringBuffer response = new StringBuffer();
                    String inputLine;
                    while ((inputLine = reader.readLine()) != null) {
                        response.append(inputLine);
                    }
                    reader.close();
                    // to log the response code of your request
                    Log.d("MyApp", "MyHttpRequestTask doInBackground : " + httpURLConnection.getResponseCode());

                    res = response.toString();
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    // this is done so that there are no open connections left when this task is going to complete
                    httpURLConnection.disconnect();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return res;
        }
    }
}

No comments:

Post a Comment

Popular Posts