Handling HTTP GET method in Android

Hi… Android amigos… 🙂 Today we are going to communicate with a server page but  insecure way. Why I’m saying “insecure” is we are using HTTP GET method for the communication. All the values that user sends to the server, embedded with the URL that we send as the request, where a third party can easily watch it. If I say it more technical way, by using the HTTP GET method, we are sending user details in the header part of the request not in the body.

But there are places we only need a HTTP GET method. Also there is a solution for the problem that others sneaking around our data packets we send as request to the server. That is using HTTP POST which is going to be my next post 😉

As usual, my interfaces are so simple. Lets begin with the interfaces that you are going to see at the end of the implementation of this HTTP GET project. Figure 1 is the one and only UI we have in our project.

HTTP GET method in Android
Figure 1

After user provides a username and a password and click the “Send GET Req” button, it start to communicate with the server. What we are doing in background is, getting the user inputs and embed them in to a URL and send a server request. If the relevant server page able to catch our parameters that we send, our target is complete. That means we have successfully communicate with a server page by using HTTP GET method.

Additionally what I have done here is, passing two parameters that contains the values for username and password. If the server page we are trying to communicate, able to read those parameters and the content values it carries, it will send the response according to that.

HTTP GET method in Android

Figure 2

First I will show you the JAVA code I have written for this Android project.

package com.anuja.httpget;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MyHttpGetProjectActivity extends Activity implements OnClickListener {

	private EditText usernameEditText;
	private EditText passwordEditText;
	private Button sendGetReqButton;

    /** Called when the activity is first created. */
    public void onCreate(Bundle savedInstanceState) {

        usernameEditText = (EditText) findViewById(R.id.main_username_editText);
        passwordEditText = (EditText) findViewById(R.id.main_password_editText);

        sendGetReqButton = (Button) findViewById(R.id.main_sendGetReq_button);

	public void onClick(View v) {

		if(v.getId() == R.id.main_sendGetReq_button){

			// Get the values given in EditText fields
			String givenUsername = usernameEditText.getText().toString();
			String givenPassword = passwordEditText.getText().toString();
			System.out.println("Given usernames is :" + givenUsername + " Given password is :" + givenPassword);

			// Pass those values to connectWithHttpGet() method
			connectWithHttpGet(givenUsername, givenPassword);

	private void connectWithHttpGet(String givenUsername, String givenPassword) {

		// Connect with a server is a time consuming process.
		//Therefore we use AsyncTask to handle it
		// From the three generic types;
		//First type relate with the argument send in execute()
		//Second type relate with onProgressUpdate method which I haven't use in this code
		//Third type relate with the return type of the doInBackground method, which also the input type of the onPostExecute method
		class HttpGetAsyncTask extends AsyncTask<String, Void, String>{

			protected String doInBackground(String... params) {

				// As you can see, doInBackground has taken an Array of Strings as the argument
				//We need to specifically get the givenUsername and givenPassword
				String paramUsername = params[0];
				String paramPassword = params[1];
				System.out.println("paramUsername is :" + paramUsername + " paramPassword is :" + paramPassword);

				// Create an intermediate to connect with the Internet
				HttpClient httpClient = new DefaultHttpClient();

				// Sending a GET request to the web page that we want
				// Because of we are sending a GET request, we have to pass the values through the URL
				HttpGet httpGet = new HttpGet("http://www.nirmana.lk/hec/android/getLogin.php?paramUsername=" + paramUsername + "&paramPassword=" + paramPassword);

				try {
					// execute(); executes a request using the default context.
					// Then we assign the execution result to HttpResponse
					HttpResponse httpResponse = httpClient.execute(httpGet);

					// getEntity() ; obtains the message entity of this response
					// getContent() ; creates a new InputStream object of the entity.
					// Now we need a readable source to read the byte stream that comes as the httpResponse
					InputStream inputStream = httpResponse.getEntity().getContent();

					// We have a byte stream. Next step is to convert it to a Character stream
					InputStreamReader inputStreamReader = new InputStreamReader(inputStream);

					// Then we have to wraps the existing reader (InputStreamReader) and buffer the input
					BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

					// InputStreamReader contains a buffer of bytes read from the source stream and converts these into characters as needed.
					//The buffer size is 8K
					//Therefore we need a mechanism to append the separately coming chunks in to one String element
					// We have to use a class that can handle modifiable sequence of characters for use in creating String
					StringBuilder stringBuilder = new StringBuilder();

					String bufferedStrChunk = null;

					// There may be so many buffered chunks. We have to go through each and every chunk of characters
					//and assign a each chunk to bufferedStrChunk String variable
					//and append that value one by one to the stringBuilder
					while((bufferedStrChunk = bufferedReader.readLine()) != null){

					// Now we have the whole response as a String value.
					//We return that value then the onPostExecute() can handle the content
					System.out.println("Returning value of doInBackground :" + stringBuilder.toString());

					// If the Username and Password match, it will return "working" as response
					// If the Username or Password wrong, it will return "invalid" as response					
					return stringBuilder.toString();

				} catch (ClientProtocolException cpe) {
					System.out.println("Exception generates caz of httpResponse :" + cpe);
				} catch (IOException ioe) {
					System.out.println("Second exception generates caz of httpResponse :" + ioe);

				return null;

			// Argument comes for this method according to the return type of the doInBackground() and
			//it is the third generic type of the AsyncTask
			protected void onPostExecute(String result) {

					Toast.makeText(getApplicationContext(), "HTTP GET is working...", Toast.LENGTH_LONG).show();
					Toast.makeText(getApplicationContext(), "Invalid...", Toast.LENGTH_LONG).show();

		// Initialize the AsyncTask class
		HttpGetAsyncTask httpGetAsyncTask = new HttpGetAsyncTask();
		// Parameter we pass in the execute() method is relate to the first generic type of the AsyncTask
		// We are passing the connectWithHttpGet() method arguments to that
		httpGetAsyncTask.execute(givenUsername, givenPassword); 


Copy above code in to an IDE, where you can easily separate comments from the code and read those comments carefully. There I have explained all the functions and reason for why I am using those functions and classes etc.

I will give you the code of the web page which I am accessing using HTTP GET method. Then you will be able to understand the response you get clearly. Following content comes in a PHP page. According to my program it name as “getLogin.php”


$varUsername = $_GET['paramUsername'];
$varPassword = $_GET['paramPassword'];

if($varUsername == "anuja" && $varPassword == "123"){
	echo 'working';
	echo 'invalid';


Simply that is all about for the today’s blog post. Before end this post I would like to thanks all friends in “Nirmana” for hosting my above web page 🙂

See you soon… amigos… 😀

About AnujAroshA

Working as an Associate Technical Lead. Specialized in iOS application development. A simple person :)
This entry was posted in Android Examples and tagged , , , , , , . Bookmark the permalink.

12 Responses to Handling HTTP GET method in Android

  1. aMIT sURI says:

    Hi Anuj, Nice post but i have one question in my mind you are using static values for the name and password in php code, Can i use same android code with Dynamic values (i.e – already stored in database).

  2. Hi Anuj,very useful post..can u plz upload the source code..I think that is very important to us…Thanks.

  3. rumi says:

    I need help ..
    im trying to use progressDialog on your httpget method . so can you post example on these connectWithHttpGet() 😀

  4. ravi says:

    hey buddy you can upload the whole android project??

  5. stan says:

    can you please do a make a source code for the same type with http post request instead of get request , so that i can post to http the username and password with an api

  6. Fede says:

    can you send me the source code??? thanks

  7. Raj says:

    Thanks dear………
    It’s really Helpful:)

  8. dude thank you i finally understand

  9. Rakhi Dhavale says:

    Hey thanks a lot for this example, I’m so grateful to you, coz its easy to understand ! I tried it out and it works smooth as butter 🙂 exactly the way u’ve mentioned in the screen shots above!

  10. Pratibha says:

    Thanks a lot

  11. Divya says:

    I have tried using java code for same.. is tat okey

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 )

Google photo

You are commenting using your Google 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 )

Connecting to %s