2015-12-07

Objective

Our main aim is to send the post and get request through our android application.

Step 1

Introduction

In this tutorial,  we are going to learn about HTTP/HTTPS POST & GET Request. Http is an underlying protocol used by world wide web. Post and Get are two most commonly used Http methods for request and response btw client and 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.

Step 4

Create layout show response

In activity_main.xml file, add two button named “Send POST Request” and “Send GET Request” and set 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 follow the code written below:



Step 5

Send Post Request

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

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

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

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 writeprimitive Java data types to an output stream.

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 the efficient reading of characters, arrays, and lines.

Set the response in TextView.

Execute it by calling its setPostRequest method.

Here is the final code for PostClass :



Step 6

Send Get Request

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

Create another class and name it GetClass.

Change the request method from POST to GET like

Remove the DataOutPutStream code because we don’t have to send the parameters for post request. Then your final code will be like.

Execute it by calling sendGetRequest method.

Step 7

Final code of MainActivity.java file

Show more