Android POST and GET Request using HttpURLConnection Tutorial

Objective

In the tutorial we learn how to send the POST and GET HTTP/HTTPS requests through our android application.

In this tutorial,  we are going to learn about HTTP/HTTPS POST & GET Requests. Http is an underlying protocol used by world wide web. POST and GET are two most commonly used HTTP methods for request and response between the client and the server. GET method basically requests data from specified resource, whereas Post method submits data to be processed to a specified resource.

 

Step 2

Create new project

1. Create a new project in Android Studio. File => New => New Project.

2. Give the application name and then click Next. Select the platform and API and then click Next.

3. Select Empty Activity and click Next. Give the activity name or you can use default name.

4. And finally click Finish.

 

Step 3

Give Permission

You need to provide some permissions to access the internet from your application. So, open your AndroidManifest.xml file and add the following code snippet.

1
<uses-permission android:name="android.permission.INTERNET"/>

 

Step 4

Create layout show response

  1. In activity_main.xml file, add two button named “Send POST Request” and “Send GET Request” and set an on click listener to them. Methods called on onClick() method will be sendPostRequest() and sendGetRequest() respectively.
  2. Add TextView and give it a unique id. So that we can show the response in the textview by calling its id. You can use the code written below:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Send POST Request"
    android:id="@+id/sendPost"
    android:layout_alignParentTop="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_alignRight="@+id/sendGet"
    android:layout_alignEnd="@+id/sendGet"
    android:onClick="sendPostRequest"/>
<Button
    style="?android:attr/buttonStyleSmall"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Send GET Request"
    android:id="@+id/sendGet"
    android:layout_below="@+id/sendPost"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true"
    android:onClick="sendGetRequest"/>
<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Response..."
    android:id="@+id/showOutput"
    android:layout_below="@+id/sendGet"
    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true" />

 

screen_1

Step 5

Send Post Request

    1. We have to create a class which sends Post request asynchronously.
      1
      2
      3
      4
      5
      6
      private class PostClass extends AsyncTask<String, Void, Void> {
         @Override
         protected Void doInBackground(String... params) {
             return null;
         }
      }
    2. Get the textview context, then set a url using URL class and parameters in a string.
      1
      2
      3
      final TextView outputView = (TextView) findViewById(R.id.showOutput);
      URL url = new URL("Your URL");</pre>
      <pre>String urlParameters = "fizz=buzz";
    3. Now open the connection using HttpURLConnection and set its properties like method, user_agent and language.
      1
      2
      3
      4
      5
      HttpURLConnection connection = (HttpURLConnection)url.openConnection();
      connection.setRequestMethod("POST");
      connection.setRequestProperty("USER-AGENT", "Mozilla/5.0");
      connection.setRequestProperty("ACCEPT-LANGUAGE", "en-US,en;0.5");
      connection.setDoOutput(true);  // You need to set it to true if you want to send (output) a request body, for example with POST or PUT requests. Sending the request body itself is done via the connection's output stream:
    4. Now, we have to use DataOutPutStream for controlling the output. We can do multiple operation on output stream using DataOutPutStream, It also helps us to write primitive Java data types to an output stream.
      1
      2
      3
      4
      DataOutputStream dStream = new DataOutputStream(connection.getOutputStream());
      dStream.writeBytes(urlParameters); //Writes out the string to the underlying output stream as a sequence of bytes
      dStream.flush(); // Flushes the data output stream.
      dStream.close(); // Closing the output stream.
    5. Next step in the process would be getting the response from server using BufferedReader. It reads text from a character-input stream, buffering characters so as to provide for efficient reading of characters, arrays, and lines.
      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      int responseCode = connection.getResponseCode(); // getting the response code
      final StringBuilder output = new StringBuilder("Request URL " + url);
      output.append(System.getProperty("line.separator") + "Request Parameters " + urlParameters);
      output.append(System.getProperty("line.separator")  + "Response Code " + responseCode);
      BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
      String line = "";
      StringBuilder responseOutput = new StringBuilder();
      System.out.println("output===============" + br);
      while((line = br.readLine()) != null ) {
         responseOutput.append(line);
      }
      br.close();
      output.append(System.getProperty("line.separator") + "Response " + System.getProperty("line.separator") + System.getProperty("line.separator") + responseOutput.toString());
    6. Set the response in TextView.
      1
      2
      3
      4
      5
      6
      7
      8
      MainActivity.this.runOnUiThread(new Runnable() {
         @Override
         public void run() {
             outputView.setText(output);;
         }
      });
    7. Execute it by calling its setPostRequest method.
      1
      2
      3
      public void sendPostRequest(View View) {
         new PostClass(this).execute();
      }

Here is the final code for PostClass :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
public void sendPostRequest(View View) {
    new PostClass(this).execute();
}
private class PostClass extends AsyncTask<String, Void, Void> {
    private final Context context;
    public PostClass(Context c){
        this.context = c;
    }
    protected void onPreExecute(){
        progress= new ProgressDialog(this.context);
        progress.setMessage("Loading");
        progress.show();
    }
    @Override
    protected Void doInBackground(String... params) {
        try {
            final TextView outputView = (TextView) findViewById(R.id.showOutput);
            URL url = new URL("Your URL");
            HttpURLConnection connection = (HttpURLConnection)url.openConnection();
            String urlParameters = "fizz=buzz";
            connection.setRequestMethod("POST");
            connection.setRequestProperty("USER-AGENT", "Mozilla/5.0");
            connection.setRequestProperty("ACCEPT-LANGUAGE", "en-US,en;0.5");
            connection.setDoOutput(true);
            DataOutputStream dStream = new DataOutputStream(connection.getOutputStream());
            dStream.writeBytes(urlParameters);
            dStream.flush();
            dStream.close();
            int responseCode = connection.getResponseCode();
            final StringBuilder output = new StringBuilder("Request URL " + url);
            output.append(System.getProperty("line.separator") + "Request Parameters " + urlParameters);
            output.append(System.getProperty("line.separator")  + "Response Code " + responseCode);
            output.append(System.getProperty("line.separator")  + "Type " + "POST");
            BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line = "";
            StringBuilder responseOutput = new StringBuilder();
            System.out.println("output===============" + br);
            while((line = br.readLine()) != null ) {
                responseOutput.append(line);
            }
            br.close();
            output.append(System.getProperty("line.separator") + "Response " + System.getProperty("line.separator") + System.getProperty("line.separator") + responseOutput.toString());
            MainActivity.this.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    outputView.setText(output);
                    progress.dismiss();
                }
            });
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }
}

screen_2

screen_3

 

Step 6

Send Get Request

Now we are going to send the GET HTTP request. For this, we need to change a few lines in the above code.

  1. Create another class and name it GetClass.
    1
    2
    3
    4
    5
    6
    private class GetClass extends AsyncTask<String, Void, Void> {
         @Override
         protected Void doInBackground(String... params) {
         }
    }
  2. Change the request method from POST to GET
    1
    connection.setRequestMethod("GET");
  3. Remove the DataOutPutStream code because we don’t have to send the parameters for post request.
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
        private class GetClass extends AsyncTask<String, Void, Void> {
            private final Context context;
            public GetClass(Context c){
                this.context = c;
            }
            protected void onPreExecute(){
                progress= new ProgressDialog(this.context);
                progress.setMessage("Loading");
                progress.show();
            }
            @Override
            protected Void doInBackground(String... params) {
                try {
                    final TextView outputView = (TextView) findViewById(R.id.showOutput);
                    URL url = new URL("Your URL");</pre>
    <pre>
     HttpURLConnection connection = (HttpURLConnection)url.openConnection();
     String urlParameters = "fizz=buzz";
     connection.setRequestMethod("GET");
     connection.setRequestProperty("USER-AGENT", "Mozilla/5.0");
     connection.setRequestProperty("ACCEPT-LANGUAGE", "en-US,en;0.5");
     int responseCode = connection.getResponseCode();
     final StringBuilder output = new StringBuilder("Request URL " + url);
     output.append(System.getProperty("line.separator") + "Response Code " + responseCode);
     output.append(System.getProperty("line.separator") + "Type " + "GET");
     BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
     String line = "";
     StringBuilder responseOutput = new StringBuilder();
     System.out.println("output===============" + br);
     while((line = br.readLine()) != null ) {
     responseOutput.append(line);
     }
     br.close();
     output.append(System.getProperty("line.separator") + "Response " + System.getProperty("line.separator") + System.getProperty("line.separator") + responseOutput.toString());
     MainActivity.this.runOnUiThread(new Runnable() {
     @Override
     public void run() {
     outputView.setText(output);
     progress.dismiss();
     }
     });
     } catch (MalformedURLException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
     } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
     }
     return null;
     }
     }
  4. Execute it by calling sendGetRequest method.
    1
    2
    3
    public void sendGetRequest(View View) {
        new GetClass(this).execute();
    }

screen_5

screen_6

 

Step 7

Final code of MainActivity.java file

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
package com.numetriclabz.sendrequests;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends Activity {
    private ProgressDialog progress;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
    public void sendPostRequest(View View) {
        new PostClass(this).execute();
    }
    public void sendGetRequest(View View) {
        new GetClass(this).execute();
    }
    private class PostClass extends AsyncTask<String, Void, Void> {
        private final Context context;
        public PostClass(Context c){
            this.context = c;
        }
        protected void onPreExecute(){
            progress= new ProgressDialog(this.context);
            progress.setMessage("Loading");
            progress.show();
        }
        @Override
        protected Void doInBackground(String... params) {
            try {
                final TextView outputView = (TextView) findViewById(R.id.showOutput);
                URL url = new URL("Your URL");</pre>
<pre>
 HttpURLConnection connection = (HttpURLConnection)url.openConnection();
 String urlParameters = "fizz=buzz";
 connection.setRequestMethod("POST");
 connection.setRequestProperty("USER-AGENT", "Mozilla/5.0");
 connection.setRequestProperty("ACCEPT-LANGUAGE", "en-US,en;0.5");
 connection.setDoOutput(true);
 DataOutputStream dStream = new DataOutputStream(connection.getOutputStream());
 dStream.writeBytes(urlParameters);
 dStream.flush();
 dStream.close();
 int responseCode = connection.getResponseCode();
 System.out.println("\nSending 'POST' request to URL : " + url);
 System.out.println("Post parameters : " + urlParameters);
 System.out.println("Response Code : " + responseCode);
 final StringBuilder output = new StringBuilder("Request URL " + url);
 output.append(System.getProperty("line.separator") + "Request Parameters " + urlParameters);
 output.append(System.getProperty("line.separator") + "Response Code " + responseCode);
 output.append(System.getProperty("line.separator") + "Type " + "POST");
 BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
 String line = "";
 StringBuilder responseOutput = new StringBuilder();
 System.out.println("output===============" + br);
 while((line = br.readLine()) != null ) {
 responseOutput.append(line);
 }
 br.close();
 output.append(System.getProperty("line.separator") + "Response " + System.getProperty("line.separator") + System.getProperty("line.separator") + responseOutput.toString());
 MainActivity.this.runOnUiThread(new Runnable() {
 @Override
 public void run() {
 outputView.setText(output);
 progress.dismiss();
 }
 });
 } catch (MalformedURLException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
 } catch (IOException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
 }
 return null;
 }
 protected void onPostExecute() {
 progress.dismiss();
 }
 }
 private class GetClass extends AsyncTask<String, Void, Void> {
 private final Context context;
 public GetClass(Context c){
 this.context = c;
 }
 protected void onPreExecute(){
 progress= new ProgressDialog(this.context);
 progress.setMessage("Loading");
 progress.show();
 }
 @Override
 protected Void doInBackground(String... params) {
 try {
 final TextView outputView = (TextView) findViewById(R.id.showOutput);
 URL url = new URL("Your URL");</pre>
<pre>
 HttpURLConnection connection = (HttpURLConnection)url.openConnection();
 String urlParameters = "fizz=buzz";
 connection.setRequestMethod("GET");
 connection.setRequestProperty("USER-AGENT", "Mozilla/5.0");
 connection.setRequestProperty("ACCEPT-LANGUAGE", "en-US,en;0.5");
 int responseCode = connection.getResponseCode();
 final StringBuilder output = new StringBuilder("Request URL " + url);
 output.append(System.getProperty("line.separator") + "Response Code " + responseCode);
 output.append(System.getProperty("line.separator") + "Type " + "GET");
 BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
 String line = "";
 StringBuilder responseOutput = new StringBuilder();
 System.out.println("output===============" + br);
 while((line = br.readLine()) != null ) {
 responseOutput.append(line);
 }
 br.close();
 output.append(System.getProperty("line.separator") + "Response " + System.getProperty("line.separator") + System.getProperty("line.separator") + responseOutput.toString());
 MainActivity.this.runOnUiThread(new Runnable() {
 @Override
 public void run() {
 outputView.setText(output);
 progress.dismiss();
 }
 });
 } catch (MalformedURLException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
 } catch (IOException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
 }
 return null;
 }
 }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s