Handling HTTP POST method in Android

Hello Androidies… 🙂 Today I am going to talk about handling HTTP POST method in an Android program. This is little bit relate to my previous post which I have explained the same scenario for GET method. POST method is more secure when we transfer confidential data to a different location by using HTTP. The reason is the content goes inside the body, not with the header as in GET method.

Let me explain the scenario that I am going to accomplish with this blog post. I want to send some confidential data to a different server by using one of my native Android application. In the server side there is a PHP page listen to the parameters that I am passing and grab relevant data.

This is the UI (User Interface) part for this project.

HTTP POST method in Android
Figure 1

Actually, giving a username and a password is something additional when we concern about our main requirement. Our main requirement is sending a request to a web page by using HTTP POST method and listen to the response if it succeed. Additionally what I have done here is, prompting a Toast message if we get a response. Figure 2 shows the possible Toast messages that you will get. But understand clearly, that is NOT the response we get from the server. That is something we hard code in our program to show for the user, after getting the response.

HTTP POST method in Android
Figure 2

Are we ready to dive in to the source code 😀 Don’t forget to copy the code in to an IDE and read the comments, because I have explained the logic in the code and I am not going to repeat it here again.

package com.anuja.httppost;

 * @author AnujAroshA

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

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 MyHttpPostProjectActivity extends Activity implements OnClickListener {

	private EditText usernameEditText;
	private EditText passwordEditText;
	private Button sendPostReqButton;
	private Button clearButton;

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

        usernameEditText = (EditText) findViewById(R.id.login_username_editText);
        passwordEditText = (EditText) findViewById(R.id.login_password_editText);

        sendPostReqButton = (Button) findViewById(R.id.login_sendPostReq_button);

        clearButton = (Button) findViewById(R.id.login_clear_button);

	public void onClick(View v) {

		if(v.getId() == R.id.login_clear_button){
		}else if(v.getId() == R.id.login_sendPostReq_button){
			String givenUsername = usernameEditText.getEditableText().toString();
			String givenPassword = passwordEditText.getEditableText().toString();

			System.out.println("Given username :" + givenUsername + " Given password :" + givenPassword);

			sendPostRequest(givenUsername, givenPassword);

	private void sendPostRequest(String givenUsername, String givenPassword) {

		class SendPostReqAsyncTask extends AsyncTask<String, Void, String>{

			protected String doInBackground(String... params) {

				String paramUsername = params[0];
				String paramPassword = params[1];

				System.out.println("*** doInBackground ** paramUsername " + paramUsername + " paramPassword :" + paramPassword);

				HttpClient httpClient = new DefaultHttpClient();

				// In a POST request, we don't pass the values in the URL.
				//Therefore we use only the web page URL as the parameter of the HttpPost argument
				HttpPost httpPost = new HttpPost("http://www.nirmana.lk/hec/android/postLogin.php");

				// Because we are not passing values over the URL, we should have a mechanism to pass the values that can be
				//uniquely separate by the other end.
				//To achieve that we use BasicNameValuePair				
				//Things we need to pass with the POST request
				BasicNameValuePair usernameBasicNameValuePair = new BasicNameValuePair("paramUsername", paramUsername);
				BasicNameValuePair passwordBasicNameValuePAir = new BasicNameValuePair("paramPassword", paramPassword);

				// We add the content that we want to pass with the POST request to as name-value pairs
				//Now we put those sending details to an ArrayList with type safe of NameValuePair
				List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();

				try {
					// UrlEncodedFormEntity is an entity composed of a list of url-encoded pairs. 
					//This is typically useful while sending an HTTP POST request. 
					UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(nameValuePairList);

					// setEntity() hands the entity (here it is urlEncodedFormEntity) to the request.

					try {
						// HttpResponse is an interface just like HttpPost.
						//Therefore we can't initialize them
						HttpResponse httpResponse = httpClient.execute(httpPost);

						// According to the JAVA API, InputStream constructor do nothing. 
						//So we can't initialize InputStream although it is not an interface
						InputStream inputStream = httpResponse.getEntity().getContent();

						InputStreamReader inputStreamReader = new InputStreamReader(inputStream);

						BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

						StringBuilder stringBuilder = new StringBuilder();

						String bufferedStrChunk = null;

						while((bufferedStrChunk = bufferedReader.readLine()) != null){

						return stringBuilder.toString();

					} catch (ClientProtocolException cpe) {
						System.out.println("First Exception caz of HttpResponese :" + cpe);
					} catch (IOException ioe) {
						System.out.println("Second Exception caz of HttpResponse :" + ioe);

				} catch (UnsupportedEncodingException uee) {
					System.out.println("An Exception given because of UrlEncodedFormEntity argument :" + uee);

				return null;

			protected void onPostExecute(String result) {

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

		SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask();
		sendPostReqAsyncTask.execute(givenUsername, givenPassword);		

Compare above code set with the HTTP GET method code set that I have posted in my previous post. Then you will get a clear idea about what I have changed, where I have changed and why I have changed that code set. Don’t forget to see the differences in the PHP pages also 😉


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

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


Now time for wrap-up. Thanks “Nirman” for hosting my “postLogin.php”.

Let’s meet with something different in next time 🙂

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.

27 Responses to Handling HTTP POST method in Android

  1. Great!! I will Try 😀 Hope Help my problem thx

  2. Vlatko says:

    How to post method from one activity where I only have one text box and a button, when I click on the button to call my php script from a local machine, and we just have to print a name on the screen phone? I hope you understand me. 🙂

  3. rahul says:

    good tutorial …searching for that in web from a long tim.
    thnx dear.

  4. vinay says:

    thank you sir

  5. ehej says:

    good , easy & fast ,,,, works Thanks

  6. Your article Handling HTTP POST method in Android | Anu’s crazy world write very well, thank you share!

  7. deepan says:

    i searching for this almost a day, i didn’t get any proper idea. thankfull to you. i did the job….

  8. Ammar says:

    Thank you very much, very clean code and very helpful comments ! It saved me from wasting another day 🙂 please keep it up

  9. Andrew says:

    Спасибо чувак!

  10. Nashif says:

    thank u

  11. thanks your code is work 😀
    thanks a lot 🙂

  12. Johne929 says:

    Just wanna remark on couple of general issues, The web site style is perfect, the subject matter is rattling excellent egcfffckdfda

  13. Johnk612 says:

    Hello! Someone in my Facebook group shared this website with us so I came to check it out. I’m definitely enjoying the information. I’m bookmarking and will be tweeting this to my followers! Outstanding blog and superb design and style. ebefdackbggf

  14. Ruslan says:

    Thx bro! Grazie! 😀

  15. Arihant says:

    yaar help me too access the data over server using .net web API in jsont format.

  16. But sir one question is that in my case if the user name is a phone number what we will do…????

  17. Khawaja Hamed says:

    thank you for your code

  18. Levis66 says:

    Nice tutorial sir but when i post correct username and password still it displays “Invalid post request” any solution to this problem?

  19. Pradeep Tiwari says:

    Nice post. worth going through. But I have a question.

    SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask();
    sendPostReqAsyncTask.execute(givenUsername, givenPassword);

    In the last line you are creating an object for the class SendPostReqAsyncTask and then accessing execute method. But there is no execute method in the class so it is giving me an error. Please elaborate, why this method is being used?

  20. MP says:

    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(“”);
    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    HttpResponse response = httpclient.execute(httppost);
    HttpEntity entity = response.getEntity();
    is = entity.getContent();
    Log.e(“pass 1”, “connection success “);

    I Need Brief explaination for the above code.and what are the paramrters to be passed for HttpPost Class

  21. praveen KUmar says:

    it is not working for me Any Body Plz Help Me In Same Process

  22. praveen KUmar says:

    it is not working for me Any Body Plz Help Me In Same Process (naani.creator@gmail.com)

  23. Maneendra says:

    hiiiii Anuja,

    Thank you very much, a great article….
    So happy to follow a article written by a batch mate.


  24. Wilmot says:

    This helped me. Thank you.

  25. AK khan says:

    Hi guyz any body tell me. this is my code. coming some error… it is no resolve httpPost and httpClient. but i dont understand… plz tell me how i solve this sulotion…

    package com.example.akdawran.loginandroid;

    import java.util.ArrayList;
    import java.util.List;

    import org.apache.http.HttpResponse;
    import org.apache.http.NameValuePair;
    import org.apache.http.client.HttpClient;
    import org.apache.http.client.ResponseHandler;
    import org.apache.http.client.entity.UrlEncodedFormEntity;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.impl.client.BasicResponseHandler;
    import org.apache.http.impl.client.DefaultHttpClient;
    import org.apache.http.message.BasicNameValuePair;

    import android.app.Activity;
    import android.app.AlertDialog;
    import android.app.ProgressDialog;
    import android.content.Context;
    import android.content.DialogInterface;
    import android.content.Intent;
    import android.content.SharedPreferences;
    import android.content.SharedPreferences.Editor;
    import android.net.wifi.WifiInfo;
    import android.net.wifi.WifiManager;
    import android.os.Bundle;
    import android.preference.PreferenceManager;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.CheckBox;
    import android.widget.EditText;
    import android.widget.Toast;

    public class MainActivity extends Activity {

    Button b;
    EditText et,pass;
    //TextView tv;
    CheckBox cb ;
    HttpPost httppost;
    StringBuffer buffer;
    HttpResponse response;
    HttpClient httpclient;
    List nameValuePairs;
    ProgressDialog dialog = null;
    SharedPreferences sharedpreferences;

    protected void onCreate(Bundle savedInstanceState) {

    b = (Button)findViewById(R.id.Button01);
    et = (EditText)findViewById(R.id.id);
    pass= (EditText)findViewById(R.id.password);
    // tv = (TextView)findViewById(R.id.tv);
    cb= (CheckBox) findViewById(R.id.checkBox1);
    b.setOnClickListener(new OnClickListener() {
    public void onClick(View v) {
    dialog = ProgressDialog.show(MainActivity.this, “”,
    “Validating user…”, true);
    new Thread(new Runnable() {
    public void run() {

    else {

    //Toast.makeText(getApplicationContext(), “No network”, Toast.LENGTH_LONG).show();


    private boolean checkConnectedToDesiredWifi() {
    boolean connected = false;

    String desiredMacAddress = “ac:72:89:6d:1a:56”;

    WifiManager wifiManager =
    (WifiManager) this.getSystemService(Context.WIFI_SERVICE);

    WifiInfo wifi = wifiManager.getConnectionInfo();
    if (wifi != null) {
    // get current router Mac address
    String bssid = wifi.getBSSID();
    // Toast.makeText(getApplicationContext(), bssid,Toast.LENGTH_LONG).show();
    connected = desiredMacAddress.equals(bssid);

    return connected;
    void login(){

    httpclient=new DefaultHttpClient();
    httppost= new HttpPost(“”); // make sure the url is correct.
    //add your data
    nameValuePairs = new ArrayList(2);
    // Always use the same variable name for posting i.e the android side variable name and php side variable name should be similar,
    nameValuePairs.add(new BasicNameValuePair(“id”,et.getText().toString().trim())); // $Edittext_value = $_POST[‘Edittext_value’];
    nameValuePairs.add(new BasicNameValuePair(“password”,pass.getText().toString().trim()));
    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    //Execute HTTP Post Request
    // edited by James from coderzheaven.. from here….
    ResponseHandler responseHandler = new BasicResponseHandler();
    final String response = httpclient.execute(httppost, responseHandler);
    System.out.println(“Response : ” + response);
    runOnUiThread(new Runnable() {
    public void run() {
    //tv.setText(“Response from PHP : ” + response);

    if(response.equalsIgnoreCase(“User Found”)){
    runOnUiThread(new Runnable() {
    public void run() {
    Toast.makeText(MainActivity.this,”Login Success”, Toast.LENGTH_LONG).show();


    sharedpreferences = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
    Editor edit = sharedpreferences.edit();
    edit.putString(“id”, et.getText().toString().trim());
    edit.putString(“password”, pass.getText().toString().trim());



    // startActivity(new Intent(LoginClass.this, AndroidTabAndListView.class));
    // Intent tab = new Intent(this, AndroidTabAndListView.class);
    // Bundle extras = new Bundle();
    // extras.putString(“doctor”,et.getText().toString() );
    // tab.putExtras(extras);
    // startActivity(tab);


    }catch(Exception e){
    System.out.println(“Exception : ” + e.getMessage());

    protected void onResume() {
    // TODO Auto-generated method stub

    public void showAlert(){
    MainActivity.this.runOnUiThread(new Runnable() {
    public void run() {
    AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
    builder.setTitle(“Login Failed.”);
    builder.setMessage(“User ID not Found.”)
    .setPositiveButton(“OK”, new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int id) {
    AlertDialog alert = builder.create();

    protected void onDestroy() {



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