Android Create a HTTP Request without using any third party library

Updated 26 October 2021

Save

In this blog, we will learn how to create a HTTP Request without using any library.

In Mobile App Development , we usually depend on a server and to make a connection with the server, we need to create http calls.
For this purpose we use networking libraries in our project so that we can easily create the http request for our use.
Some of the popular libraries are Volley, Retrofit etc.

Of course, these libraries help us a lot and make our work easy and our calls faster.

But what if we don’t wan to use any of these libraries.

Let us see how to do this :

APPROACH :

  1. You need to create an Async Task that will be running on background thread.
    P.S : The Android developers have restricted the HTTP Requests to be working on background thread.
    If you get to know any other method than Async Task , please let me know in the comments below.
  2. Pass on url and your data in the execute method of the Async Task you just created as arguments.
  3. In doInBackground() method of your Async Task extract the url and data from the arguments.
  4. Create a new Object of the URL class by passing the url of your HTTP Request.
  5. Create a Object of HttpURLConnection/HttpsURLConnection and assign it the value returned  by the openConnection() method of the URL object you created.
    Note : You need to type cast the value returned by openConnection() method into your desired HttpURLConnection/HttpsURLConnection Object.
  6. On this object set the request method Type (e.g POST , GET,PUT) by calling the function setRequestMethod() and passing the name of the request method as the argument.
  7. If you need to add headers to your request you can simply do so by calling the function setREquestProperty() and passing the header name as the first key and value as the second key.
  8. Get the output stream of your HttpURLConnection/HttpsURLConnection object.
  9. Create a new object of OutputStreamWriter by passing in the output stream obtained above.
  10. Write the data with the help of write function of the OutpuStreamWriter object you just created.
  11. Close the stream and close the connection as you have send the request.

CODE :

AsyncTask for the request :

Calling the Async Task :

That’s all you have created your first HTTP request without using any library.

Keep coding and Keep Sharing 🙂

author
. . .

Leave a Comment

Your email address will not be published. Required fields are marked*


12 comments

  • F.Selin
    Hello, Last year I was using Async Task but I realized AsyncTask caused memory leaks. I decided to change this method. Right now I am searching a new method for http request without using any library. Please let me know if you know something else.
    • anchit (Moderator)
      Hi,

      Well AsyncTask causes memory leaks, usually, this statement itself is wrong, it’s our faulty code that causes memory leaks. Still, I will not get into the depths of this topic as i don’t know what eactly is your scenario and code.

      Regarding any other approaches, I can only suggest using FutureTask or threads for each network calls (This might give you even bigger memory leaks if not handled properly).

  • Aditya
    new HttpClass().execute(my_url,my_data);

    where put this line in code ?

    • anchit (Moderator)
      You need to add this line wherever you want to execute your HTTP request.
  • Ian Paulo
    Hellp, thanks for your great tutorial. Just one question, how do i catch the response to a variable?
    Thanks
    • anchit (Moderator)
      Hello,

      In order to catch the response to a variable, you will need to modify the request and an InputStream object that will actually catch the response.

      After you get the correct InputStream, then you will need to decode the data and assign it to a variable.

      So your final AsyncTask will ideally be something like below :

      private class MyHttpRequestTask extends AsyncTask {

      @Override
      protected String doInBackground(String… params) {
      String my_url = params[0];
      String my_data = params[1];
      String final_response=””;
      try {
      URL url = new URL(my_url);
      HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
      // setting the Request Method Type
      httpURLConnection.setRequestMethod(“POST”);
      // adding the headers for request
      httpURLConnection.setRequestProperty(“Content-Type”, “application/json”);
      try {
      //to tell the connection object that we will be wrting some data on the server and then will fetch the output result
      httpURLConnection.setDoOutput(true);
      // this is used for just in case we don’t know about the data size associated with our request
      httpURLConnection.setChunkedStreamingMode(0);

      // to write the data in our request
      OutputStream outputStream = new BufferedOutputStream(httpURLConnection.getOutputStream());
      OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream);
      outputStreamWriter.write(my_data);
      outputStreamWriter.flush();
      outputStreamWriter.close();

      // to read the response data from our request
      InputStream inputStream;
      if (httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
      inputStream = new BufferedInputStream(httpURLConnection.getInputStream());
      }else {
      inputStream = new BufferedInputStream(httpURLConnection.getErrorStream());
      }

      BufferedReader reader = new BufferedReader(new InputStreamReader(
      inputStream, “UTF-8”), 8);
      StringBuilder sb = new StringBuilder();
      String line = null;
      while ((line = reader.readLine()) != null) {
      sb.append(line + “\n”);
      }
      inputStream.close();
      final_response = sb.toString();

      // to log the response code of your request
      Log.d(ApplicationConstant.TAG, “MyHttpRequestTask doInBackground : ” + httpURLConnection.getResponseCode());
      // to log the response message from your server after you have tried the request.
      Log.d(ApplicationConstant.TAG, “MyHttpRequestTask doInBackground : ” + httpURLConnection.getResponseMessage());

      } 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 final_response;
      }
      }

      NOTE : I have just looked into the explaination provided in the HttpURLConnection.java class, there might be some small glitches that might need some tuning.

      The code is not fully tested, please do check once and do let me know as well 🙂

  • Ian Paulo
    Hello*, sorry for the typo
  • Daneil
    I’m trying to figure out how I would send something in a body of the request here? I need to capture it in a server written in python, not java, but I have to send it from Java. The string I have to send it too long to hide in the URL, so I either need a way to get my_data out with basic python tools or I need to fit it into a request body. I cannot figure out how to do either, but I thought you might have an idea on how to add the body.
    • anchit (Moderator)
      Hey,

      The my_data can hold any amount of data but if you are getting string too long error, then please debug the case properly.

      Further, on the server side, you will definitely need to get the data in the request body through python tools, that will be the only way.

      Thanks.

  • William Menezes
    Plz update the code for the latest àndroid versions as I am getting avc denied and no responses
  • William Menezes
    Sir I apologize for not seeing my code properly.Instead of execute() I was calling doInBackground.Sorry for the earlier comment
    • anchit (Moderator)
      No Worries
  • Start a Project


      Message Sent!

      If you have more details or questions, you can reply to the received confirmation email.

      Back to Home