Objective
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.
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.
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 /> <uses-permission android:name="android.permission.INTERNET"/><br />
Create layout show response
- 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.
- 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 /> <Button<br /> android:layout_width="wrap_content"<br /> android:layout_height="wrap_content"<br /> android:text="Send POST Request"<br /> android:id="@+id/sendPost"<br /> android:layout_alignParentTop="true"<br /> android:layout_alignParentLeft="true"<br /> android:layout_alignParentStart="true"<br /> android:layout_alignRight="@+id/sendGet"<br /> android:layout_alignEnd="@+id/sendGet"<br /> android:onClick="sendPostRequest"/></p> <p> <Button<br /> style="?android:attr/buttonStyleSmall"<br /> android:layout_width="wrap_content"<br /> android:layout_height="wrap_content"<br /> android:text="Send GET Request"<br /> android:id="@+id/sendGet"<br /> android:layout_below="@+id/sendPost"<br /> android:layout_alignParentLeft="true"<br /> android:layout_alignParentStart="true"<br /> android:layout_alignParentRight="true"<br /> android:layout_alignParentEnd="true"<br /> android:onClick="sendGetRequest"/></p> <p> <TextView<br /> android:layout_width="fill_parent"<br /> android:layout_height="wrap_content"<br /> android:text="Response..."<br /> android:id="@+id/showOutput"<br /> android:layout_below="@+id/sendGet"<br /> android:layout_alignParentRight="true"<br /> android:layout_alignParentEnd="true" /></p> <p>
Send Post Request
- We have to create a class which sends Post request asynchronously.
<br /> private class PostClass extends AsyncTask<String, Void, Void> {<br /> @Override<br /> protected Void doInBackground(String... params) {<br /> return null;<br /> }<br /> }<br />
- 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("Your URL");</pre><br /> <pre>String urlParameters = "fizz=buzz";<br />
- 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("POST");<br /> connection.setRequestProperty("USER-AGENT", "Mozilla/5.0");<br /> connection.setRequestProperty("ACCEPT-LANGUAGE", "en-US,en;0.5");<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 />
- 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 />
- 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("Request URL " + url);<br /> output.append(System.getProperty("line.separator") + "Request Parameters " + urlParameters);<br /> output.append(System.getProperty("line.separator") + "Response Code " + responseCode);<br /> BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));<br /> String line = "";<br /> StringBuilder responseOutput = new StringBuilder();<br /> System.out.println("output===============" + br);<br /> while((line = br.readLine()) != null ) {<br /> responseOutput.append(line);<br /> }<br /> br.close();</p> <p>output.append(System.getProperty("line.separator") + "Response " + System.getProperty("line.separator") + System.getProperty("line.separator") + responseOutput.toString());<br />
- 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 />
- 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<String, Void, Void> {</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("Loading");<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("Your URL");</p> <p> HttpURLConnection connection = (HttpURLConnection)url.openConnection();<br /> String urlParameters = "fizz=buzz";<br /> connection.setRequestMethod("POST");<br /> connection.setRequestProperty("USER-AGENT", "Mozilla/5.0");<br /> connection.setRequestProperty("ACCEPT-LANGUAGE", "en-US,en;0.5");<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("Request URL " + url);<br /> output.append(System.getProperty("line.separator") + "Request Parameters " + urlParameters);<br /> output.append(System.getProperty("line.separator") + "Response Code " + responseCode);<br /> output.append(System.getProperty("line.separator") + "Type " + "POST");<br /> BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));<br /> String line = "";<br /> StringBuilder responseOutput = new StringBuilder();<br /> System.out.println("output===============" + br);<br /> while((line = br.readLine()) != null ) {<br /> responseOutput.append(line);<br /> }<br /> br.close();</p> <p> output.append(System.getProperty("line.separator") + "Response " + System.getProperty("line.separator") + System.getProperty("line.separator") + 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 />
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.
- Create another class and name it GetClass.
<br /> private class GetClass extends AsyncTask<String, Void, Void> {<br /> @Override<br /> protected Void doInBackground(String... params) {</p> <p> }<br /> }<br />
- Change the request method from POST to GET
<br /> connection.setRequestMethod("GET");<br />
- Remove the DataOutPutStream code because we don’t have to send the parameters for post request.
<br /> private class GetClass extends AsyncTask<String, Void, Void> {</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("Loading");<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("Your URL");</pre><br /> <pre><br /> HttpURLConnection connection = (HttpURLConnection)url.openConnection();<br /> String urlParameters = "fizz=buzz";<br /> connection.setRequestMethod("GET");<br /> connection.setRequestProperty("USER-AGENT", "Mozilla/5.0");<br /> connection.setRequestProperty("ACCEPT-LANGUAGE", "en-US,en;0.5");</p> <p> int responseCode = connection.getResponseCode();</p> <p> final StringBuilder output = new StringBuilder("Request URL " + url);<br /> output.append(System.getProperty("line.separator") + "Response Code " + responseCode);<br /> output.append(System.getProperty("line.separator") + "Type " + "GET");<br /> BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));<br /> String line = "";<br /> StringBuilder responseOutput = new StringBuilder();<br /> System.out.println("output===============" + br);<br /> while((line = br.readLine()) != null ) {<br /> responseOutput.append(line);<br /> }<br /> br.close();</p> <p> output.append(System.getProperty("line.separator") + "Response " + System.getProperty("line.separator") + System.getProperty("line.separator") + 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 />
- Execute it by calling sendGetRequest method.
<br /> public void sendGetRequest(View View) {<br /> new GetClass(this).execute();<br /> }<br />
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<String, Void, Void> {</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("Loading");<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("Your URL");</pre><br /> <pre><br /> HttpURLConnection connection = (HttpURLConnection)url.openConnection();<br /> String urlParameters = "fizz=buzz";<br /> connection.setRequestMethod("POST");<br /> connection.setRequestProperty("USER-AGENT", "Mozilla/5.0");<br /> connection.setRequestProperty("ACCEPT-LANGUAGE", "en-US,en;0.5");<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("\nSending 'POST' request to URL : " + url);<br /> System.out.println("Post parameters : " + urlParameters);<br /> System.out.println("Response Code : " + responseCode);</p> <p> final StringBuilder output = new StringBuilder("Request URL " + url);<br /> output.append(System.getProperty("line.separator") + "Request Parameters " + urlParameters);<br /> output.append(System.getProperty("line.separator") + "Response Code " + responseCode);<br /> output.append(System.getProperty("line.separator") + "Type " + "POST");<br /> BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));<br /> String line = "";<br /> StringBuilder responseOutput = new StringBuilder();<br /> System.out.println("output===============" + br);<br /> while((line = br.readLine()) != null ) {<br /> responseOutput.append(line);<br /> }<br /> br.close();</p> <p> output.append(System.getProperty("line.separator") + "Response " + System.getProperty("line.separator") + System.getProperty("line.separator") + 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<String, Void, Void> {</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("Loading");<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("Your URL");</pre><br /> <pre><br /> HttpURLConnection connection = (HttpURLConnection)url.openConnection();<br /> String urlParameters = "fizz=buzz";<br /> connection.setRequestMethod("GET");<br /> connection.setRequestProperty("USER-AGENT", "Mozilla/5.0");<br /> connection.setRequestProperty("ACCEPT-LANGUAGE", "en-US,en;0.5");</p> <p> int responseCode = connection.getResponseCode();</p> <p> final StringBuilder output = new StringBuilder("Request URL " + url);<br /> output.append(System.getProperty("line.separator") + "Response Code " + responseCode);<br /> output.append(System.getProperty("line.separator") + "Type " + "GET");<br /> BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));<br /> String line = "";<br /> StringBuilder responseOutput = new StringBuilder();<br /> System.out.println("output===============" + br);<br /> while((line = br.readLine()) != null ) {<br /> responseOutput.append(line);<br /> }<br /> br.close();</p> <p> output.append(System.getProperty("line.separator") + "Response " + System.getProperty("line.separator") + System.getProperty("line.separator") + 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 />