Advertisement

header ads

Android Post and Get Request Tutorial using Httpurlconnection




Introduction 

Lets look at how to 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 project

First of all you need to create a new project. So, create a new project in Android Studio, go to File => New => New Projects

Creating Asynchronous Method

Lets create an 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 need to 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://dasunsucharith.esy.es/index.php"); // Enter your server url here
 
            JSONObject postDataParams = new JSONObject();
            postDataParams.put("name", "dasun");
            postDataParams.put("email", "dasun@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 need 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://dasunsucharith.esy.es/index.php");
 
            JSONObject postDataParams = new JSONObject();
            postDataParams.put("name", "dasun");
            postDataParams.put("email", "dasun@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://dasunsucharith.esy.es/index.php"); // here is your URL path
 
            JSONObject postDataParams = new JSONObject();
            postDataParams.put("name", "dasun");
            postDataParams.put("email", "dasun@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()

We need to 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://dasunsucharith.esy.es/index.php"); // here is your URL path
 
            JSONObject postDataParams = new JSONObject();
            postDataParams.put("name", "dasun");
            postDataParams.put("email", "dasun@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://dasunsucharith.esy.es/index.php"); // here is your URL path
            JSONObject postDataParams = new JSONObject();
            postDataParams.put("name", "dasun");
            postDataParams.put("email", "dasun@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. so we use echo command in this application php code. 

<?php
$email = $_POST['email'];
$name = $_POST['name'];
echo "Data Sent Successfully";
?>
So you can add this php file to your server , inside the public file and then deploy the above application to a device or to a virtual device and then test it.

Post a Comment

1 Comments

  1. Thank you for the tutorial. Clear and so easy to follow.

    If the backend code is jsp, not php all the POST and GET still function correctly, aren't they?

    ReplyDelete