Android Httpurlconnection Post and Get Request Tutorial

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("http://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("http://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("http://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("http://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("http://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'];
echo "Data Sent Successfully";

?>

post request

  


  


The following two tabs change content below.
Abhay Anand has experience in the field of Software Development. He can program Android, PHP, JavaScript, Html, Css. He develops web and Android applications. You can reach him at anand.abhay1910@gmail.com
  • 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