Read More

Android Create a HTTP Request without using any library

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 đŸ™‚

. . .

Comments (6)

Add Your Comment

  • 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
      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
      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
      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 đŸ™‚

  • css.php
    Hire Us!
    Brief us about your requirements and we'll get back to you.
    Woo! Hooy!
    We have just recieved your project brief and our expert will contact you shortly.
    Send Again
    Close