Android POST and GET Request using HttpURLConnection Tutorial

Udemy Generic 728x90

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.

<br />
 &lt;uses-permission android:name=&quot;android.permission.INTERNET&quot;/&gt;<br />

 

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:

<br />
    &lt;Button<br />
        android:layout_width=&quot;wrap_content&quot;<br />
        android:layout_height=&quot;wrap_content&quot;<br />
        android:text=&quot;Send POST Request&quot;<br />
        android:id=&quot;@+id/sendPost&quot;<br />
        android:layout_alignParentTop=&quot;true&quot;<br />
        android:layout_alignParentLeft=&quot;true&quot;<br />
        android:layout_alignParentStart=&quot;true&quot;<br />
        android:layout_alignRight=&quot;@+id/sendGet&quot;<br />
        android:layout_alignEnd=&quot;@+id/sendGet&quot;<br />
        android:onClick=&quot;sendPostRequest&quot;/&gt;</p>
<p>    &lt;Button<br />
        style=&quot;?android:attr/buttonStyleSmall&quot;<br />
        android:layout_width=&quot;wrap_content&quot;<br />
        android:layout_height=&quot;wrap_content&quot;<br />
        android:text=&quot;Send GET Request&quot;<br />
        android:id=&quot;@+id/sendGet&quot;<br />
        android:layout_below=&quot;@+id/sendPost&quot;<br />
        android:layout_alignParentLeft=&quot;true&quot;<br />
        android:layout_alignParentStart=&quot;true&quot;<br />
        android:layout_alignParentRight=&quot;true&quot;<br />
        android:layout_alignParentEnd=&quot;true&quot;<br />
        android:onClick=&quot;sendGetRequest&quot;/&gt;</p>
<p>    &lt;TextView<br />
        android:layout_width=&quot;fill_parent&quot;<br />
        android:layout_height=&quot;wrap_content&quot;<br />
        android:text=&quot;Response...&quot;<br />
        android:id=&quot;@+id/showOutput&quot;<br />
        android:layout_below=&quot;@+id/sendGet&quot;<br />
        android:layout_alignParentRight=&quot;true&quot;<br />
        android:layout_alignParentEnd=&quot;true&quot; /&gt;</p>
<p>

 

screen_1

Step 5

Send Post Request

    1. We have to create a class which sends Post request asynchronously.

      <br />
      private class PostClass extends AsyncTask&lt;String, Void, Void&gt; {<br />
         @Override<br />
         protected Void doInBackground(String... params) {<br />
             return null;<br />
         }<br />
      }<br />
      

    2. Get the textview context, then set a url using URL class and parameters in a string. 

      <br />
      final TextView outputView = (TextView) findViewById(R.id.showOutput);<br />
      URL url = new URL(&quot;Your URL&quot;);&lt;/pre&gt;<br />
      &lt;pre&gt;String urlParameters = &quot;fizz=buzz&quot;;<br />
      

    3. Now open the connection using HttpURLConnection and set its properties like method, user_agent and language. 

      <br />
      HttpURLConnection connection = (HttpURLConnection)url.openConnection();<br />
      connection.setRequestMethod(&quot;POST&quot;);<br />
      connection.setRequestProperty(&quot;USER-AGENT&quot;, &quot;Mozilla/5.0&quot;);<br />
      connection.setRequestProperty(&quot;ACCEPT-LANGUAGE&quot;, &quot;en-US,en;0.5&quot;);<br />
      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:<br />
      

    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.

      <br />
      DataOutputStream dStream = new DataOutputStream(connection.getOutputStream());<br />
      dStream.writeBytes(urlParameters); //Writes out the string to the underlying output stream as a sequence of bytes<br />
      dStream.flush(); // Flushes the data output stream.<br />
      dStream.close(); // Closing the output stream.<br />
      

    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. 

      <br />
      int responseCode = connection.getResponseCode(); // getting the response code<br />
      final StringBuilder output = new StringBuilder(&quot;Request URL &quot; + url);<br />
      output.append(System.getProperty(&quot;line.separator&quot;) + &quot;Request Parameters &quot; + urlParameters);<br />
      output.append(System.getProperty(&quot;line.separator&quot;)  + &quot;Response Code &quot; + responseCode);<br />
      BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));<br />
      String line = &quot;&quot;;<br />
      StringBuilder responseOutput = new StringBuilder();<br />
      System.out.println(&quot;output===============&quot; + br);<br />
      while((line = br.readLine()) != null ) {<br />
         responseOutput.append(line);<br />
      }<br />
      br.close();</p>
      <p>output.append(System.getProperty(&quot;line.separator&quot;) + &quot;Response &quot; + System.getProperty(&quot;line.separator&quot;) + System.getProperty(&quot;line.separator&quot;) + responseOutput.toString());<br />
      

    6. Set the response in TextView. 

      <br />
      MainActivity.this.runOnUiThread(new Runnable() {</p>
      <p>   @Override<br />
         public void run() {<br />
             outputView.setText(output);;</p>
      <p>   }<br />
      });<br />
      

    7. Execute it by calling its setPostRequest method.

      <br />
      public void sendPostRequest(View View) {<br />
         new PostClass(this).execute();<br />
      }<br />
      

Here is the final code for PostClass : 

<br />
    public void sendPostRequest(View View) {<br />
        new PostClass(this).execute();<br />
    }</p>
<p>    private class PostClass extends AsyncTask&lt;String, Void, Void&gt; {</p>
<p>        private final Context context;</p>
<p>        public PostClass(Context c){<br />
            this.context = c;<br />
        }</p>
<p>        protected void onPreExecute(){<br />
            progress= new ProgressDialog(this.context);<br />
            progress.setMessage(&quot;Loading&quot;);<br />
            progress.show();<br />
        }</p>
<p>        @Override<br />
        protected Void doInBackground(String... params) {<br />
            try {</p>
<p>                final TextView outputView = (TextView) findViewById(R.id.showOutput);<br />
                URL url = new URL(&quot;Your URL&quot;);</p>
<p>                HttpURLConnection connection = (HttpURLConnection)url.openConnection();<br />
                String urlParameters = &quot;fizz=buzz&quot;;<br />
                connection.setRequestMethod(&quot;POST&quot;);<br />
                connection.setRequestProperty(&quot;USER-AGENT&quot;, &quot;Mozilla/5.0&quot;);<br />
                connection.setRequestProperty(&quot;ACCEPT-LANGUAGE&quot;, &quot;en-US,en;0.5&quot;);<br />
                connection.setDoOutput(true);<br />
                DataOutputStream dStream = new DataOutputStream(connection.getOutputStream());<br />
                dStream.writeBytes(urlParameters);<br />
                dStream.flush();<br />
                dStream.close();<br />
                int responseCode = connection.getResponseCode();</p>
<p>                final StringBuilder output = new StringBuilder(&quot;Request URL &quot; + url);<br />
                output.append(System.getProperty(&quot;line.separator&quot;) + &quot;Request Parameters &quot; + urlParameters);<br />
                output.append(System.getProperty(&quot;line.separator&quot;)  + &quot;Response Code &quot; + responseCode);<br />
                output.append(System.getProperty(&quot;line.separator&quot;)  + &quot;Type &quot; + &quot;POST&quot;);<br />
                BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));<br />
                String line = &quot;&quot;;<br />
                StringBuilder responseOutput = new StringBuilder();<br />
                System.out.println(&quot;output===============&quot; + br);<br />
                while((line = br.readLine()) != null ) {<br />
                    responseOutput.append(line);<br />
                }<br />
                br.close();</p>
<p>                output.append(System.getProperty(&quot;line.separator&quot;) + &quot;Response &quot; + System.getProperty(&quot;line.separator&quot;) + System.getProperty(&quot;line.separator&quot;) + responseOutput.toString());</p>
<p>                MainActivity.this.runOnUiThread(new Runnable() {</p>
<p>                    @Override<br />
                    public void run() {<br />
                        outputView.setText(output);<br />
                        progress.dismiss();<br />
                    }<br />
                });</p>
<p>            } catch (MalformedURLException e) {<br />
                // TODO Auto-generated catch block<br />
                e.printStackTrace();<br />
            } catch (IOException e) {<br />
                // TODO Auto-generated catch block<br />
                e.printStackTrace();<br />
            }<br />
            return null;<br />
        }<br />
    }<br />

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.

    <br />
    private class GetClass extends AsyncTask&lt;String, Void, Void&gt; {<br />
         @Override<br />
         protected Void doInBackground(String... params) {</p>
    <p>     }<br />
    }<br />
    

  2. Change the request method from POST to GET

    <br />
    connection.setRequestMethod(&quot;GET&quot;);<br />
    

  3. Remove the DataOutPutStream code because we don’t have to send the parameters for post request.  

    <br />
        private class GetClass extends AsyncTask&lt;String, Void, Void&gt; {</p>
    <p>        private final Context context;</p>
    <p>        public GetClass(Context c){<br />
                this.context = c;<br />
            }</p>
    <p>        protected void onPreExecute(){<br />
                progress= new ProgressDialog(this.context);<br />
                progress.setMessage(&quot;Loading&quot;);<br />
                progress.show();<br />
            }</p>
    <p>        @Override<br />
            protected Void doInBackground(String... params) {<br />
                try {</p>
    <p>                final TextView outputView = (TextView) findViewById(R.id.showOutput);<br />
                    URL url = new URL(&quot;Your URL&quot;);&lt;/pre&gt;<br />
    &lt;pre&gt;<br />
     HttpURLConnection connection = (HttpURLConnection)url.openConnection();<br />
     String urlParameters = &quot;fizz=buzz&quot;;<br />
     connection.setRequestMethod(&quot;GET&quot;);<br />
     connection.setRequestProperty(&quot;USER-AGENT&quot;, &quot;Mozilla/5.0&quot;);<br />
     connection.setRequestProperty(&quot;ACCEPT-LANGUAGE&quot;, &quot;en-US,en;0.5&quot;);</p>
    <p> int responseCode = connection.getResponseCode();</p>
    <p> final StringBuilder output = new StringBuilder(&quot;Request URL &quot; + url);<br />
     output.append(System.getProperty(&quot;line.separator&quot;) + &quot;Response Code &quot; + responseCode);<br />
     output.append(System.getProperty(&quot;line.separator&quot;) + &quot;Type &quot; + &quot;GET&quot;);<br />
     BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));<br />
     String line = &quot;&quot;;<br />
     StringBuilder responseOutput = new StringBuilder();<br />
     System.out.println(&quot;output===============&quot; + br);<br />
     while((line = br.readLine()) != null ) {<br />
     responseOutput.append(line);<br />
     }<br />
     br.close();</p>
    <p> output.append(System.getProperty(&quot;line.separator&quot;) + &quot;Response &quot; + System.getProperty(&quot;line.separator&quot;) + System.getProperty(&quot;line.separator&quot;) + responseOutput.toString());</p>
    <p> MainActivity.this.runOnUiThread(new Runnable() {</p>
    <p> @Override<br />
     public void run() {<br />
     outputView.setText(output);<br />
     progress.dismiss();</p>
    <p> }<br />
     });</p>
    <p> } catch (MalformedURLException e) {<br />
     // TODO Auto-generated catch block<br />
     e.printStackTrace();<br />
     } catch (IOException e) {<br />
     // TODO Auto-generated catch block<br />
     e.printStackTrace();<br />
     }<br />
     return null;<br />
     }<br />
     }<br />
    

  4. Execute it by calling sendGetRequest method.

    <br />
        public void sendGetRequest(View View) {<br />
            new GetClass(this).execute();<br />
        }<br />
    

screen_5

screen_6

 

Step 7

Final code of MainActivity.java file

<br />
package com.numetriclabz.sendrequests;</p>
<p>import java.io.BufferedReader;<br />
import java.io.DataOutputStream;<br />
import java.io.IOException;<br />
import java.io.InputStreamReader;<br />
import java.net.HttpURLConnection;<br />
import java.net.MalformedURLException;<br />
import java.net.URL;</p>
<p>import javax.net.ssl.HttpsURLConnection;</p>
<p>import android.app.Activity;<br />
import android.app.ProgressDialog;<br />
import android.content.Context;<br />
import android.os.AsyncTask;<br />
import android.os.Bundle;<br />
import android.support.v7.app.ActionBarActivity;<br />
import android.view.View;<br />
import android.widget.TextView;</p>
<p>public class MainActivity extends Activity {</p>
<p>    private ProgressDialog progress;</p>
<p>    @Override<br />
    protected void onCreate(Bundle savedInstanceState) {<br />
        super.onCreate(savedInstanceState);<br />
        setContentView(R.layout.activity_main);</p>
<p>    }</p>
<p>    public void sendPostRequest(View View) {<br />
        new PostClass(this).execute();<br />
    }</p>
<p>    public void sendGetRequest(View View) {<br />
        new GetClass(this).execute();<br />
    }</p>
<p>    private class PostClass extends AsyncTask&lt;String, Void, Void&gt; {</p>
<p>        private final Context context;</p>
<p>        public PostClass(Context c){<br />
            this.context = c;<br />
        }</p>
<p>        protected void onPreExecute(){<br />
            progress= new ProgressDialog(this.context);<br />
            progress.setMessage(&quot;Loading&quot;);<br />
            progress.show();<br />
        }</p>
<p>        @Override<br />
        protected Void doInBackground(String... params) {<br />
            try {</p>
<p>                final TextView outputView = (TextView) findViewById(R.id.showOutput);<br />
                URL url = new URL(&quot;Your URL&quot;);&lt;/pre&gt;<br />
&lt;pre&gt;<br />
 HttpURLConnection connection = (HttpURLConnection)url.openConnection();<br />
 String urlParameters = &quot;fizz=buzz&quot;;<br />
 connection.setRequestMethod(&quot;POST&quot;);<br />
 connection.setRequestProperty(&quot;USER-AGENT&quot;, &quot;Mozilla/5.0&quot;);<br />
 connection.setRequestProperty(&quot;ACCEPT-LANGUAGE&quot;, &quot;en-US,en;0.5&quot;);<br />
 connection.setDoOutput(true);<br />
 DataOutputStream dStream = new DataOutputStream(connection.getOutputStream());<br />
 dStream.writeBytes(urlParameters);<br />
 dStream.flush();<br />
 dStream.close();<br />
 int responseCode = connection.getResponseCode();</p>
<p> System.out.println(&quot;\nSending 'POST' request to URL : &quot; + url);<br />
 System.out.println(&quot;Post parameters : &quot; + urlParameters);<br />
 System.out.println(&quot;Response Code : &quot; + responseCode);</p>
<p> final StringBuilder output = new StringBuilder(&quot;Request URL &quot; + url);<br />
 output.append(System.getProperty(&quot;line.separator&quot;) + &quot;Request Parameters &quot; + urlParameters);<br />
 output.append(System.getProperty(&quot;line.separator&quot;) + &quot;Response Code &quot; + responseCode);<br />
 output.append(System.getProperty(&quot;line.separator&quot;) + &quot;Type &quot; + &quot;POST&quot;);<br />
 BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));<br />
 String line = &quot;&quot;;<br />
 StringBuilder responseOutput = new StringBuilder();<br />
 System.out.println(&quot;output===============&quot; + br);<br />
 while((line = br.readLine()) != null ) {<br />
 responseOutput.append(line);<br />
 }<br />
 br.close();</p>
<p> output.append(System.getProperty(&quot;line.separator&quot;) + &quot;Response &quot; + System.getProperty(&quot;line.separator&quot;) + System.getProperty(&quot;line.separator&quot;) + responseOutput.toString());</p>
<p> MainActivity.this.runOnUiThread(new Runnable() {</p>
<p> @Override<br />
 public void run() {<br />
 outputView.setText(output);<br />
 progress.dismiss();<br />
 }<br />
 });</p>
<p> } catch (MalformedURLException e) {<br />
 // TODO Auto-generated catch block<br />
 e.printStackTrace();<br />
 } catch (IOException e) {<br />
 // TODO Auto-generated catch block<br />
 e.printStackTrace();<br />
 }<br />
 return null;<br />
 }</p>
<p> protected void onPostExecute() {<br />
 progress.dismiss();<br />
 }</p>
<p> }</p>
<p> private class GetClass extends AsyncTask&lt;String, Void, Void&gt; {</p>
<p> private final Context context;</p>
<p> public GetClass(Context c){<br />
 this.context = c;<br />
 }</p>
<p> protected void onPreExecute(){<br />
 progress= new ProgressDialog(this.context);<br />
 progress.setMessage(&quot;Loading&quot;);<br />
 progress.show();<br />
 }</p>
<p> @Override<br />
 protected Void doInBackground(String... params) {<br />
 try {</p>
<p> final TextView outputView = (TextView) findViewById(R.id.showOutput);<br />
 URL url = new URL(&quot;Your URL&quot;);&lt;/pre&gt;<br />
&lt;pre&gt;<br />
 HttpURLConnection connection = (HttpURLConnection)url.openConnection();<br />
 String urlParameters = &quot;fizz=buzz&quot;;<br />
 connection.setRequestMethod(&quot;GET&quot;);<br />
 connection.setRequestProperty(&quot;USER-AGENT&quot;, &quot;Mozilla/5.0&quot;);<br />
 connection.setRequestProperty(&quot;ACCEPT-LANGUAGE&quot;, &quot;en-US,en;0.5&quot;);</p>
<p> int responseCode = connection.getResponseCode();</p>
<p> final StringBuilder output = new StringBuilder(&quot;Request URL &quot; + url);<br />
 output.append(System.getProperty(&quot;line.separator&quot;) + &quot;Response Code &quot; + responseCode);<br />
 output.append(System.getProperty(&quot;line.separator&quot;) + &quot;Type &quot; + &quot;GET&quot;);<br />
 BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));<br />
 String line = &quot;&quot;;<br />
 StringBuilder responseOutput = new StringBuilder();<br />
 System.out.println(&quot;output===============&quot; + br);<br />
 while((line = br.readLine()) != null ) {<br />
 responseOutput.append(line);<br />
 }<br />
 br.close();</p>
<p> output.append(System.getProperty(&quot;line.separator&quot;) + &quot;Response &quot; + System.getProperty(&quot;line.separator&quot;) + System.getProperty(&quot;line.separator&quot;) + responseOutput.toString());</p>
<p> MainActivity.this.runOnUiThread(new Runnable() {</p>
<p> @Override<br />
 public void run() {<br />
 outputView.setText(output);<br />
 progress.dismiss();</p>
<p> }<br />
 });</p>
<p> } catch (MalformedURLException e) {<br />
 // TODO Auto-generated catch block<br />
 e.printStackTrace();<br />
 } catch (IOException e) {<br />
 // TODO Auto-generated catch block<br />
 e.printStackTrace();<br />
 }<br />
 return null;<br />
 }<br />
 }<br />
}<br />

Udemy Generic 728x90

Spread the word. Share this post!

  • sf

    Cannot resolve symbol ‘HttpURLConnection’
    Cannot resolve symbol ‘URL’

    • Prathap Reddy

      add http core and client libs

  • Frank Høvin

    Have you even looked at your post before publishing it? IT’S FULL OF HTML CODE!

  • Sandeep M Das

    Genius….
    Written by Trump?

  • Oscar

    Hi!
    Can this code be written so you send a JSON object to an url using POST request? If that is the case, how would one do that?