Android Httpurlconnection Post and Get Request Tutorial

65

In this tutorial, we will learn how to send HTTP Post Request to server using httpurlconnection from Android App.

Introduction

We will create a connection between Android App and server at certain period then send or receive the data request from Android App to server.



Create a new poject

Create a new project in Android Studio, goto File ⇒ New ⇒ New Projects.

 

Creating Asynchronous method

We will create a Asynchronous method called as SendPostRequest() in MainActivity.java file. Asynchronous method operates independently of other processes. It will execute the process in background.

 

public class MainActivity extends AppCompatActivity {
   

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public class SendPostRequest extends AsyncTask<String, Void, String> {

        protected void onPreExecute(){}

        protected String doInBackground(String... arg0) {}

        @Override
        protected void onPostExecute(String result) {}
    }
}

 

Creating URL and JSONObject

Now, we need to define url in Asynchronous method and also we will initialize the JSONObject and add your data into JSONObject as a key value pair.

public class MainActivity extends AppCompatActivity {
   

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public class SendPostRequest extends AsyncTask<String, Void, String> {

        protected void onPreExecute(){}

        protected String doInBackground(String... arg0) {
          
         try{

            URL url = new URL("https://studytutorial.in/post.php");

            JSONObject postDataParams = new JSONObject();
            postDataParams.put("name", "abc");
            postDataParams.put("email", "abc@gmail.com");
            Log.e("params",postDataParams.toString());
         }
         catch(Exception e){
             return new String("Exception: " + e.getMessage());
         }

        }

        @Override
        protected void onPostExecute(String result) {
           
        }
    }
}

 

Creating URL and JSONObject

We will use an URLConnection for HTTP used to send and receive data over the web and also create a HttpURLConnectionn by calling URL.openConnection() and casting the result to HttpURLConnection and also set the connection timeout, method type and must be configured with setDoInput(true).

public class MainActivity extends AppCompatActivity {
   

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
       
    }

    public class SendPostRequest extends AsyncTask<String, Void, String> {

        protected void onPreExecute(){}

        protected String doInBackground(String... arg0) {
         
          try{

            URL url = new URL("https://studytutorial.in/post.php");

            JSONObject postDataParams = new JSONObject();
            postDataParams.put("name", "abc");
            postDataParams.put("email", "abc@gmail.com");
            Log.e("params",postDataParams.toString());

            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(15000 /* milliseconds */);
            conn.setConnectTimeout(15000 /* milliseconds */);
            conn.setRequestMethod("POST");
            conn.setDoInput(true);
            conn.setDoOutput(true);
         }
         catch(Exception e){
            return new String("Exception: " + e.getMessage());
         }

        }

        @Override
        protected void onPostExecute(String result) {}
    }
}

 

Creating a method to convert JSONObject to encode url string format

We need to make a string return type method called as getPostDataString(). This method is convenient when encoding a string to be used in a query part of a URL.

public class MainActivity extends AppCompatActivity {
   

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public class SendPostRequest extends AsyncTask<String, Void, String> {
      try{ 

        protected void onPreExecute(){}

        protected String doInBackground(String... arg0) {
            
            URL url = new URL("https://studytutorial.in/post.php"); // here is your URL path

            JSONObject postDataParams = new JSONObject();
            postDataParams.put("name", "abc");
            postDataParams.put("email", "abc@gmail.com");
            Log.e("params",postDataParams.toString());

            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(15000 /* milliseconds */);
            conn.setConnectTimeout(15000 /* milliseconds */);
            conn.setRequestMethod("POST");
            conn.setDoInput(true);
            conn.setDoOutput(true);
       }
       catch(Exception e){
           return new String("Exception: " + e.getMessage());
       }

        }

        @Override
        protected void onPostExecute(String result) {
           
        }
    }

    public String getPostDataString(JSONObject params) throws Exception {

        StringBuilder result = new StringBuilder();
        boolean first = true;

        Iterator<String> itr = params.keys();

        while(itr.hasNext()){

            String key= itr.next();
            Object value = params.get(key);

            if (first)
                first = false;
            else
                result.append("&");

            result.append(URLEncoder.encode(key, "UTF-8"));
            result.append("=");
            result.append(URLEncoder.encode(value.toString(), "UTF-8"));

        }
        return result.toString();
    }
}

 

Return the response in onPostExecute()

Firstly, we will encode the url string of JSONObject. This url string send the server to get the response. we get the response via getInputStream(). And read the response through StringBuffer object. Return the response string into onPostExcute() method.

public class MainActivity extends AppCompatActivity {
   

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
    }

    public class SendPostRequest extends AsyncTask<String, Void, String> {

        protected void onPreExecute(){}

        protected String doInBackground(String... arg0) {

          try {

            URL url = new URL("https://studytutorial.in/post.php"); // here is your URL path

            JSONObject postDataParams = new JSONObject();
            postDataParams.put("name", "abc");
            postDataParams.put("email", "abc@gmail.com");
            Log.e("params",postDataParams.toString());

            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(15000 /* milliseconds */);
            conn.setConnectTimeout(15000 /* milliseconds */);
            conn.setRequestMethod("POST");
            conn.setDoInput(true);
            conn.setDoOutput(true);

             OutputStream os = conn.getOutputStream();
                BufferedWriter writer = new BufferedWriter(
                        new OutputStreamWriter(os, "UTF-8"));
                writer.write(getPostDataString(postDataParams));

                writer.flush();
                writer.close();
                os.close();

                int responseCode=conn.getResponseCode();

                if (responseCode == HttpsURLConnection.HTTP_OK) {

                    BufferedReader in=new BufferedReader(
                               new InputStreamReader(
                                 conn.getInputStream()));
                    StringBuffer sb = new StringBuffer("");
                    String line="";

                    while((line = in.readLine()) != null) {

                        sb.append(line);
                        break;
                    }

                    in.close();
                    return sb.toString();

                }
                else {
                    return new String("false : "+responseCode);
                }
            }
            catch(Exception e){
                return new String("Exception: " + e.getMessage());
            }

        }

        @Override
        protected void onPostExecute(String result) {
           Toast.makeText(getApplicationContext(), result,
                    Toast.LENGTH_LONG).show();
        }
    }

    public String getPostDataString(JSONObject params) throws Exception {

        StringBuilder result = new StringBuilder();
        boolean first = true;

        Iterator<String> itr = params.keys();

        while(itr.hasNext()){

            String key= itr.next();
            Object value = params.get(key);

            if (first)
                first = false;
            else
                result.append("&");

            result.append(URLEncoder.encode(key, "UTF-8"));
            result.append("=");
            result.append(URLEncoder.encode(value.toString(), "UTF-8"));

        }
        return result.toString();
    }
}

 

Call the SendPostRequest() method to Post Request

Now, we can call the SendPostRequest() method to send and receive data from the server end. here is final MainActivity.java file

public class MainActivity extends AppCompatActivity {
   

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        new SendPostRequest().execute();
        
    }

    public class SendPostRequest extends AsyncTask<String, Void, String> {

        protected void onPreExecute(){}

        protected String doInBackground(String... arg0) {

          try {

            URL url = new URL("https://studytutorial.in/post.php"); // here is your URL path

            JSONObject postDataParams = new JSONObject();
            postDataParams.put("name", "abc");
            postDataParams.put("email", "abc@gmail.com");
            Log.e("params",postDataParams.toString());

            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(15000 /* milliseconds */);
            conn.setConnectTimeout(15000 /* milliseconds */);
            conn.setRequestMethod("POST");
            conn.setDoInput(true);
            conn.setDoOutput(true);

             OutputStream os = conn.getOutputStream();
                BufferedWriter writer = new BufferedWriter(
                        new OutputStreamWriter(os, "UTF-8"));
                writer.write(getPostDataString(postDataParams));

                writer.flush();
                writer.close();
                os.close();

                int responseCode=conn.getResponseCode();

                if (responseCode == HttpsURLConnection.HTTP_OK) {

                    BufferedReader in=new BufferedReader(new 
                           InputStreamReader(
                                  conn.getInputStream()));

                    StringBuffer sb = new StringBuffer("");
                    String line="";

                    while((line = in.readLine()) != null) {

                        sb.append(line);
                        break;
                    }

                    in.close();
                    return sb.toString();

                }
                else {
                    return new String("false : "+responseCode);
                }
            }
            catch(Exception e){
                return new String("Exception: " + e.getMessage());
            }

        }

        @Override
        protected void onPostExecute(String result) {
           Toast.makeText(getApplicationContext(), result,
                    Toast.LENGTH_LONG).show();
        }
    }

    public String getPostDataString(JSONObject params) throws Exception {

        StringBuilder result = new StringBuilder();
        boolean first = true;

        Iterator<String> itr = params.keys();

        while(itr.hasNext()){

            String key= itr.next();
            Object value = params.get(key);

            if (first)
                first = false;
            else
                result.append("&");

            result.append(URLEncoder.encode(key, "UTF-8"));
            result.append("=");
            result.append(URLEncoder.encode(value.toString(), "UTF-8"));

        }
        return result.toString();
    }
}

 

PHP Backend Code

Here is the PHP code that gets request from Android Application and return response( To return response, we need to print data).

<?php 
$email = $_POST['email'];
$name = $_POST['name'];
print_r(json_encode($_POST));

?>

post request




  • John

    thanks alot for your post , but source code link is not working ,plz update it , thanks again

    • Hi Jhon,

      I am glad, it helped you and thanks to inform me. I have updated download link. Please check

      • nayan

        HI Jhon,

        thank you for the post, but the source code download link is not working.

        • abhayanand1910

          Thanks to inform me….now download link is working

  • Jeffy

    Why am I getting response code as 301?

  • Jeffy

    Tutorail is really great. Could you please suggest me some online server where i could try this POST method

  • Jeffy

    Could you please bring up the blog for update and delete?

    • Its backend process. For update and delete, you can do this process on your server. I cannot do this.

  • Jeffy

    What should I do with the html tag code that you send me? My system has some issue with virtual android phone. So i am looking to run the code on my android phone that requires a real server

  • Vikram Kumar

    This is great tutorial, It helped me

    • abhayanand1910

      Glad it helped you.

  • Kepi Agrawal

    Thanx, it was very helpful .. 🙂

    • abhayanand1910

      Glad it helped you

  • fayzal

    Thank you, very helpful

    • abhayanand1910

      Glad it helped you

  • destar android

    Hi thank you for help but I am getting ON POST EXECUTE: false : 400 and some time ON POST EXECUTE: false : 500

    • abhayanand1910

      if you got 400 in response, means there is a problem in your back-end code. Please check your code.

  • Diego Silang

    sir can you post or share the sample receiving code of the PHP as well? thank you very much.

    • abhayanand1910

      Hi Diego,
      Here is the PHP code that get the request from Android APP and return response.

      • Diego Silang

        thank you very much!!!

        • abhayanand1910

          Welcome..

    • abhayanand1910

      Hi Diego,
      I have added PHP code in the tutorial, I hope, It will help you.

      • Diego Silang

        thank you sir!!!

  • Fazil T.M

    Sir can you add with file share. Send multipart file using post method.

  • Richard Vega HZ

    Hello, i understand the code but i tried in android studio bit with a localhost, but thrwos me an connection failure in the catch, the error ocurrs when the code reach the OutputStream, thank for the help…

    • abhayanand1910

      You can not make a connection between a localhost and android studio. Plz use server

  • Abhishek Rathod

    I am able to establish connection successfully but the data does not get stored in the database.
    Here is my code:

    init.php has database variables.

    When I go to the URL from browser data gets inserted but not from the Android app.
    Plsz Help 🙂

  • Ray Vaniya

    nothings happens….

    its only toast “false : 301”

  • Ray Vaniya

    nothings happens….

    its only toast “false : 400”

    i am running your code(no modification)

    • Error in your backend code plz check again

  • praveen singh

    hi abhay
    please provide full code for admin login on android app

    • Hi Praveen,
      This tutorial explains, How to send request to Server. You need to create a form In which you get login credentials and send to server. Then validate it and send your response.

  • Welcome

  • Kanhaiya Kumar Chowdhary

    Dear Mr Anand
    I am trying to make an android app of this website
    http://exam.nitp.ac.in:9001/
    the first thing it requires is sending username and password
    so how to do that
    how should i start , what should i use httpUrlConnection or httpClient
    with get method or post method
    please help me atleast give me some hint so that i can start my work

    note:- this website is in form of .aspx i think its not in php

    • Hi Kanhaiya,

      Ye need to make a login form and send the request to your server to verify and login via HttpUrlConnection.

  • arun

    hi
    i am using asp.net webmethods..I am returning a object with multiple values..
    how do I catch the return object and extract various values in android.

  • Nagendra Hari Karthick

    Hi thank you sharing such a wonderful tutorial i am getting an error something like false:201.what should i do?

    • I think, you are containing Etag respone in header. You need to send response as Json.

      • Nagendra Hari Karthick

        Thanks i removed the if statement now the error is gone!!

  • Varsha Vikshith

    hai ….
    can you give me the post.php code what ever you give in this site is just 3 lines but in my view some thing is there apart from that ie converting those 2 variables into JSON….#than you advance

    • $email = $_POST[’email’];
      $name = $_POST[‘name’];
      print_r(json_encode($_POST));

  • fuzzypickle

    Hey i am trying to implement this code you have put out, but my only problem is that i am getting an exception of: Exception Permission denied and i am not too sure what is? I am using my laptop as the local host and using xampp as the msq connection. Apache and mysql on xampp are running fine.

    • You want to get data from database using php then you need to use ‘SELECT’ Command.

      • fuzzypickle

        Thanks! One more question for you. I am now trying to send 4 values to the php server and this is how i have it set up on the andorid side:

        postDataParams.put(“name”, “goerge”);
        postDataParams.put(“email”, “guest@guest.com”);
        postDataParams.put(“last”, “wayne”);
        postDataParams.put(“profile”, “hello world”);

        and this is the php side:

        $con=mysqli_connect(“localhost”,”username”,”password”,”database”);

        $email = $_POST[’email’];
        $name = $_POST[‘name’];
        $last = $_POST[‘last’]
        //$profile = $_POST[‘profile’]

        //print_r(json_encode($_POST));

        $sql=”INSERT INTO author_add (authorFirst, authorLast, email,profile) VALUES (‘$name’, ‘$last’,’$email’,’$profile’)”;

        But i am getting a return statement of: “”. I am wanting to understand why i am getting that response and how to fix it. I haven changed any of the code you gave. Thanks

  • fuzzypickle

    Hey, I am having another issue. I have tried to add another 2 data parameters to send to php server. The only thing is now it wont send at all and i am getting back a string of “”. The only thing i changed/added was the 2 dataparameters and then on php i added the two values into strings just like we did to the original two. Am i missing something? Here is my code:

    Android:
    postDataParams.put(“name”, “goerge”);
    postDataParams.put(“email”, “example”);
    postDataParams.put(“myLast”, “wayne”);
    postDataParams.put(“myProfile”, “wayne”);

    PHP:
    $email = $_POST[’email’];
    $name = $_POST[‘name’];
    $last = $_POST[‘myLast’]
    $profile = $_POST[‘myProfile’]

    $sql=”INSERT INTO author_add (authorFirst, authorLast, email,profile) VALUES (‘$name’,’$last’,’$email’,’#profile’)”;

    the only change being made is the $last, and $profile addition. I don’t get why it wont send to the database when using the original two parameters worked fine. Any help would be gratefully appreciated!

  • Shiva Singhal

    WHERE IS THE GET METHOD

  • Henrik Gilvad

    you really should add
    } finally { conn.disconnect(); }

  • Nagendra Hari Karthick

    Say my json contains some value like “name”:null, I want to process it in response post execute
    But the code does not allow null values to return,

    while((line = in.readLine()) != null) {

    sb.append(line);
    break;
    }
    What should i do?

  • Bassu Rai

    hi Abhay Anand
    i want to get JSON using this process, how can i get it, its return me “false : 405”