Android: how to post http request


Step 1: prepare a simple Endpoint API to test.

I.e. http://demo.tutorialspots.com/android/postdata/login.php

<?php

if(isset($_POST['user']) && isset($_POST['pass']) && $_POST['user']!="" && $_POST['pass']!=""){
    echo "done";
}

Step 2: create new android project

Step 3: create the layout res\layout\activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.tutorialspots.postdata.MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TUTORIALSPOTS.COM"
        android:textColor="#FF0000"
        android:textSize="30dp"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:id="@+id/textView" />

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:inputType="textPersonName"
        android:hint="Name:"
        android:ems="10"
        android:id="@+id/user"
        android:layout_below="@+id/textView"
        android:layout_centerHorizontal="true" />

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:inputType="textPassword"
        android:ems="10"
        android:hint="Pass:"
        android:id="@+id/pass"
        android:layout_below="@+id/user"
        android:layout_centerHorizontal="true" />

    <Button
        style="?android:attr/buttonStyleSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Reset"
        android:id="@+id/resetBtn"
        android:layout_below="@+id/pass"
        android:layout_alignLeft="@+id/pass"
        android:layout_alignStart="@+id/pass" />

    <Button
        style="?android:attr/buttonStyleSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Login"
        android:id="@+id/submitBtn"
        android:layout_below="@+id/pass"
        android:layout_alignRight="@+id/pass"
        android:layout_alignEnd="@+id/pass" />


</RelativeLayout>

android http post data example

Step 4: open file app\build.gradle

add:

compile 'org.apache.httpcomponents:httpcore:4.0'
    compile 'org.apache.httpcomponents:httpmime:4.0'

and

packagingOptions {
        exclude 'META-INF/DEPENDENCIES'
        exclude 'META-INF/NOTICE'
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/LICENSE.txt'
        exclude 'META-INF/NOTICE.txt'
    }

    useLibrary 'org.apache.http.legacy'

The full code of file app\build.gradle

apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.2"

    defaultConfig {
        applicationId "com.tutorialspots.postdata"
        minSdkVersion 15
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    packagingOptions {
        exclude 'META-INF/DEPENDENCIES'
        exclude 'META-INF/NOTICE'
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/LICENSE.txt'
        exclude 'META-INF/NOTICE.txt'
    }

    useLibrary 'org.apache.http.legacy'
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.1.1'
    compile 'org.apache.httpcomponents:httpcore:4.0'
    compile 'org.apache.httpcomponents:httpmime:4.0'
}

Click Sync Now

android http post data example 2

Step 5: file AndroidManifest.xml

add

<uses-permission android:name="android.permission.INTERNET" />

Step 6: file MainActivity.java

package com.tutorialspots.postdata;

import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

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 org.apache.http.HttpResponse;

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

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private EditText userEditText;
    private EditText passEditText;
    private Button sendButton;
    private Button clearButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        userEditText = (EditText) findViewById(R.id.user);
        passEditText = (EditText) findViewById(R.id.pass);

        sendButton = (Button) findViewById(R.id.submitBtn);
        sendButton.setOnClickListener(this);

        clearButton = (Button) findViewById(R.id.resetBtn);
        clearButton.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {

        if(v.getId() == R.id.resetBtn){
            userEditText.setText("");
            passEditText.setText("");
            passEditText.setCursorVisible(false);
            passEditText.setFocusable(true);
            userEditText.setCursorVisible(true);
        }else if(v.getId() == R.id.submitBtn){
            String givenUsername = userEditText.getEditableText().toString();
            String givenPassword = passEditText.getEditableText().toString();

            Log.d("POSTDATA", "user :" + givenUsername + ", pass :" + givenPassword);

            sendPostRequest(givenUsername, givenPassword);
        }
    }

    private void sendPostRequest(String user, String pass) {

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

            @Override
            protected String doInBackground(String... strings) {

                String user = strings[0];
                String pass = strings[1];

                Log.d("POSTDATA", "doInBackground: user " + user + " pass :" + pass);

                HttpClient httpClient = new DefaultHttpClient();

                HttpPost httpPost = new HttpPost("http://demo.tutorialspots.com/android/postdata/login.php");

                BasicNameValuePair userBasicNameValuePair = new BasicNameValuePair("user", user);
                BasicNameValuePair passBasicNameValuePAir = new BasicNameValuePair("pass", pass);

                List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
                nameValuePairList.add(userBasicNameValuePair);
                nameValuePairList.add(passBasicNameValuePAir);

                try {
                    UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(nameValuePairList);
                    httpPost.setEntity(urlEncodedFormEntity);

                    try {
                        // Execute http post
                        HttpResponse httpResponse = httpClient.execute(httpPost);
                        InputStream inputStream = httpResponse.getEntity().getContent();
                        InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
                        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
                        String content = "";
                        String line = null;
                        while((line = bufferedReader.readLine()) != null){
                            content += line;
                        }
                        return content;
                    } catch (ClientProtocolException cpe) {
                        cpe.printStackTrace();
                    } catch (IOException ioe) {
                        ioe.printStackTrace();
                    }
                } catch (UnsupportedEncodingException uee) {
                    uee.printStackTrace();
                }
                return null;
            }

            @Override
            protected void onPostExecute(String result) {
                if(result.equals("done")){
                    Toast.makeText(getApplicationContext(), "HTTP POST is working", Toast.LENGTH_LONG).show();
                }else{
                    Toast.makeText(getApplicationContext(), "Invalid POST request data", Toast.LENGTH_LONG).show();
                }
            }
        }

        SendAsyncTask sendAsyncTask = new SendAsyncTask();
        sendAsyncTask.execute(user, pass);
    }
}

Step 7: run for test

android http post data example 3

Leave a Reply