Android HttpClient

In this blog post, you can learn android source code on how to post data to a url by using a httpclient post method.

Please find below the very simple android source code example for dealing with httpclient post. This simple code executes a http post request with org.apache.http.client.HttpClient and can be used in the combination with Non-Blocking Web Requests.


public void postData() {
    // Create a new HttpClient and Post Header
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("http://www.website.com/phpscript.php");

    try {
        // Add your data
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
        nameValuePairs.add(new BasicNameValuePair("id", "9449"));
        nameValuePairs.add(new BasicNameValuePair("stringdata", "android"));
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        // Execute HTTP Post Request
        HttpResponse response = httpclient.execute(httppost);
        
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
    } catch (IOException e) {
        // TODO Auto-generated catch block
    }

Creating HTTP Client and HTTP Post

// Creating a HTTP client
HttpClient httpClient = new DefaultHttpClient();

// Creating a HTTP Post
HttpPost httpPost = new HttpPost("http://www.androidsourcecodeexamples.com/index");


Create post parameters with key and value.

List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(2);
nameValuePair.add(new BasicNameValuePair("email", "xxx@gmail.com"));
nameValuePair.add(new BasicNameValuePair("password", "xxx_password"));


At last we should execute the httpPost using httpClient which is created previously.

// Making HTTP Request
try {
    HttpResponse response = httpClient.execute(httpPost);

    // writing response to log
    Log.d("Http Response:", response.toString());

} catch (ClientProtocolException e) {
    // writing exception to log
    e.printStackTrace();
         
} catch (IOException e) {
    // writing exception to log
    e.printStackTrace();
}


Please find below the full android code units to make a http Request. This example is for response to the log. For http response see your eclipse log report.


package com.udhaya.httprequests;

import java.io.IOException;
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.Bundle;
import android.util.Log;


public class AndroidHTTPRequestsActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);


        // Creating HTTP client

        HttpClient httpClient = new DefaultHttpClient();
        // Creating HTTP Post
        HttpPost httpPost = new HttpPost("http://www.example.com/login");


        // Building post parameters

        // key and value pair
        List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(2);
        nameValuePair.add(new BasicNameValuePair("email", "xxx@gmail.com"));
        nameValuePair.add(new BasicNameValuePair("sms",android http post"));


        // Url Encoding the POST parameters

        try {
            httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
        } catch (UnsupportedEncodingException e) {
            // writing error to Log
            e.printStackTrace();
        }


        // Making HTTP Request

        try {
            HttpResponse response = httpClient.execute(httpPost);


            // writing response to log

            Log.d("Http Response:", response.toString());
        } catch (ClientProtocolException e) {
            // writing exception to log
            e.printStackTrace();
        } catch (IOException e) {
            // writing exception to log
            e.printStackTrace();


        }

    }
}

Android JSON Example

In this post, you an learn how to decode the JSON data which is in encoded format in Android using few source code examples. Here we are going to see an example of JSON reading in android.
Let us have a simple PHP web service which encodes the string array into JSON format. I'm going to access that web service using Android http client and then it decodes the JSON data.

Consider a simple web service in PHP which encodes the string array in JSON format.

<?php
$data = array('name' => 'android', 'version' => 'Android 2.3'); 
print (json_encode($data)); 
?>


Now consider the following activity_main.xml


<?xml version="1.0" encoding="utf-8"?>
<AbsoluteLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
    <TextView


        android:id="@+id/textView1"

        android:layout_width="216dp"
        android:layout_height="36dp"
        android:layout_weight="1"
        android:layout_x="66dp"
        android:layout_y="192dp"
        android:textAppearance="?android:attr/textAppearanceMedium" />
 </AbsoluteLayout>

Add Uses permission to the android manifest xml file.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.json.php"
    android:versionCode="1"
    android:versionName="1.0" >
     <uses-sdk android:minSdkVersion="8" />
    <uses-permission android:name="android.permission.INTERNET"/>
     <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".JSONExampleActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                 <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
 </manifest>

Now activitymain.java

package com.json.php;
import android.app.Activity;
import android.os.Bundle;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import android.widget.TextView;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;


public class JSONExampleActivity extends Activity {

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://udhayacode.tk/json_android_example.php");
        TextView textView = (TextView)findViewById(R.id.textView1);
  try {
   
   HttpResponse response = httpclient.execute(httppost);
   String jsonResult = inputStreamToString(response.getEntity().getContent()).toString();
   JSONObject object = new JSONObject(jsonResult);



   String name = object.getString("name");

      String verion = object.getString("version");
      textView.setText(name + " - " + verion);
     
  } 
  catch (JSONException e) {
   e.printStackTrace();
  } 
  catch (ClientProtocolException e) {
   e.printStackTrace();
  } 
  catch (IOException e) {
   e.printStackTrace();
  }
 }
    private StringBuilder inputStreamToString(InputStream is) {
        String rLine = "";
        StringBuilder answer = new StringBuilder();
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));
          
        try {
         while ((rLine = rd.readLine()) != null) {
          answer.append(rLine);
           }
        }
          
        catch (IOException e) {
            e.printStackTrace();
         }
        return answer;
       }
}

Android Get IP Address

In this post, you can learn android source code to fetch the internet network IP address of the android device. Create a new android project and then in the main activity update the below code units.

ActivityMain.java

package com.udhaya.ip;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
public class MainActivity extends Activity {
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  try {
   for (Enumeration en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
              NetworkInterface intf = en.nextElement();
              for (Enumeration enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
                  InetAddress inetAddress = enumIpAddr.nextElement();
                  if (!inetAddress.isLoopbackAddress()) {
                  TextView ipView= (TextView) findViewById(R.string.ip);
                  ipView.setText(inetAddress.getHostAddress());
                  }
              }
          }
  } catch (Exception e) {
   Log.e("------------", e.toString());
  }
   }
}

Also, in the android manifest file, update the Uses Permission as mentioned below.
       
 <uses-permission android:name="android.permission.INTERNET" />

Android Code to Send Email

There are numerous mobile android applications in which the email option has been integrated and nowadays in professional official mobile applications in android has the email option featured within the app. In this post you can learn on writing android codes on how to send an email. It will ask for gmail client.

The below android source code is an example to send Email from an android application. Include this in the activity file of your project and the work is done and thats it.

Intent mAndroidEmailIntent = new Intent (android.content.Intent.ACTION_SEND); String aEmailList[] = { "android@gmail.com","android@yahoo.com" }; mAndroidEmailIntent.putExtra (android.content.Intent.EXTRA_EMAIL, aEmailList); mAndroidEmailIntent.putExtra (android.content.Intent.EXTRA_SUBJECT, "Mail Subject"); mAndroidEmailIntent.setType ("plain/text"); mAndroidEmailIntent.putExtra (android.content.Intent.EXTRA_TEXT, "Email From My Android App"); startActivity (mAndroidEmailIntent); 

Now let us see the steps for sending email in an android app in brief below.

1.  Create the Activity_Main.xml file
activity_main.xml

<LinearLayout 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:orientation="vertical" >
    <EditText
        android:id="@+id/editText_emailAdd"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="Enter Email"
        android:inputType="textEmailAddress" >
    </EditText>
    <EditText
        android:id="@+id/editText_subject"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="Subject" >
    </EditText>
    <MultiAutoCompleteTextView
        android:id="@+id/multiAutoCompleteTextView_message"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="Message" >
    </MultiAutoCompleteTextView>
    <Button
        android:id="@+id/button_send"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="Send " />
</LinearLayout>


2. Now create the ActivityMain.java file
ActivityMain.java

package com.udhaya.sendemail;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class ActivityMain extends Activity {
    TextView emailadd, sub, message;
    Button btnsend;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        emailadd = (TextView) findViewById(R.id.editText_emailAdd);
        sub = (TextView) findViewById(R.id.editText_subject);
        message = (TextView) findViewById(R.id.multiAutoCompleteTextView_message);
        btnsend = (Button) findViewById(R.id.button_send);
        btnsend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                String emailAddress = emailadd.getText().toString();
                String emailSubject = sub.getText().toString();
                String emailMessage = message.getText().toString();
                // below source code is the key for sending the email                Intent emailIntent = new Intent(
                        android.content.Intent.ACTION_SEND);
                emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL,
                        emailAddress);
                emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,
                        emailSubject);
                emailIntent.setType("plain/text");
                emailIntent.putExtra(android.content.Intent.EXTRA_TEXT,
                        emailMessage);
                startActivity(emailIntent);
            }
        });
    }
}


3. Now work on the Android Manifest file. Add the below Uses Permission for internet options.
   <uses-permission android:name="android.permission.INTERNET"/>

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.udhaya.sendemail"
    android:versionCode="1"
    android:versionName="1.0" >
    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />
   <uses-permission android:name="android.permission.INTERNET"/>

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.udhaya.sendemail.ActivityMain"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
My Profile