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

Don't Miss

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&amp;lt;String&amp;gt; itr = params.keys();

        while(itr.hasNext()){

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

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

            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&amp;amp;lt;String, Void, String&amp;amp;gt; {

        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 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 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();
    }
}

</string,>

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

79 COMMENTS

  1. 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

  2. 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…

  3. 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 🙂

    • 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.

  4. 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

  5. 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.

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

  7. 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

  8. 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.

      • 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

  9. 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!

  10. 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?

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

    sb.append(line);
    break;
    }

    can you please tell me what is the purpose of break statement within while block.
    I checked but I found no use of it within it.

LEAVE A REPLY

Please enter your comment!
Please enter your name here

564FansLike

Recent Posts

Concept of Session in Laravel Tutorial

Sessions are used to store details about the user throughout the requests. Laravel supplies various drivers like file, cookie, apc, array, Memcached, Redis, and database to handle session data. By default, file driver is used as a result of it's light-weight....

Laravel Url Generation Tutorial

Our web application revolves around routes and URLs. After all, they're what direct our users to our pages. At the end of the day, serving pages is what any web application should do. Our users may...

Concept of Laravel Views Tutorial

In MVC framework, the letter "V" stands for Views. It separates the application logic and presentation logic. Views are saved in resources/views listing. Generally, the view contains the HTML which might be served by the application.

Related Articles

Concept of Session in Laravel Tutorial

Sessions are used to store details about the user throughout the requests. Laravel supplies various drivers like file, cookie, apc, array, Memcached, Redis, and database to handle session data. By default, file driver is used as a result of it's light-weight....

Laravel Url Generation Tutorial

Our web application revolves around routes and URLs. After all, they're what direct our users to our pages. At the end of the day, serving pages is what any web application should do. Our users may...

Concept of Laravel Views Tutorial

In MVC framework, the letter "V" stands for Views. It separates the application logic and presentation logic. Views are saved in resources/views listing. Generally, the view contains the HTML which might be served by the application.
WP2Social Auto Publish Powered By : XYZScripts.com