HttpClient in Android

Introduction

 
This article explains how to post data using HttpClient in Android. Android Studio is used to create the sample.
 
HttpClient is used when you want to receive and send data from the server over the internet. So for this you need to create a http client using HttpClient class. First, you will create the object of Http client and the URL to the constructor of HttpPost class that post the data. Now create the data that you want to send to the server. Set the entity with the data and get the response by ing httppost to the constructor of HttpResponse that returns the response. Get the statusLine that the send data is valid or not. If the status code returns by the getStatus() are 200 it means your data is sent. 
 
Step 1
 
Create a project like this:
 
image which show data
 
Step 2
 
Create a an XML file and write this
  1. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  2.     xmlns:tools="http://schemas.android.com/tools"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="match_parent"  
  5.     android:paddingLeft="@dimen/activity_horizontal_margin"  
  6.     android:paddingRight="@dimen/activity_horizontal_margin"  
  7.     android:paddingTop="@dimen/activity_vertical_margin"  
  8.     android:paddingBottom="@dimen/activity_vertical_margin"  
  9.     tools:context=".MainActivity">  
  10.    
  11.     <TextView  
  12.         android:layout_width="wrap_content"  
  13.         android:layout_height="wrap_content"  
  14.         android:text="@string/hello_world" />  
  15.    
  16. </RelativeLayout> 
Step 3
 
Create a Java class file with the following:
  1. package com.androidhttpclient;  
  2.    
  3. import java.io.IOException;  
  4. import java.io.UnsupportedEncodingException;  
  5. import java.util.ArrayList;  
  6. import java.util.List;  
  7. import org.apache.http.HttpResponse;  
  8. import org.apache.http.NameValuePair;  
  9. import org.apache.http.StatusLine;  
  10. import org.apache.http.client.ClientProtocolException;  
  11. import org.apache.http.client.HttpClient;  
  12. import org.apache.http.client.entity.UrlEncodedFormEntity;  
  13. import org.apache.http.client.methods.HttpPost;  
  14. import org.apache.http.impl.client.DefaultHttpClient;  
  15. import org.apache.http.message.BasicNameValuePair;  
  16.    
  17. import android.annotation.TargetApi;  
  18. import android.app.Activity;  
  19. import android.os.Build;  
  20. import android.os.Bundle;  
  21. import android.os.StrictMode;  
  22. import android.util.Log;  
  23.    
  24. public class MainActivity extends Activity {  
  25.     @TargetApi(Build.VERSION_CODES.GINGERBREAD)  
  26.     @Override  
  27.     public void onCreate(Bundle savedInstanceState) {  
  28.         super.onCreate(savedInstanceState);  
  29.         setContentView(R.layout.activity_main);  
  30.         if (android.os.Build.VERSION.SDK_INT > 9) {  
  31.             StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();  
  32.             StrictMode.setThreadPolicy(policy);  
  33.         }  
  34.         // Creating HTTP client  
  35.         HttpClient Client = new DefaultHttpClient();  
  36.         // Creating HTTP Post  
  37.         HttpPost Post = new HttpPost(  
  38.                 "http://androidexample.com/media/webservice/httppost.php");  
  39.    
  40.         Log.d("HTTPPSt",""+Post);  
  41.         // Building post parameters  
  42.         // key and value pair  
  43.         List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(2);  
  44.         nameValuePair.add(new BasicNameValuePair("name""username"));  
  45.         nameValuePair.add(new BasicNameValuePair("word","8090509239"));  
  46.    
  47.         // Url Encoding the POST parameters  
  48.         try {  
  49.             Post.setEntity(new UrlEncodedFormEntity(nameValuePair));  
  50.         } catch (UnsupportedEncodingException e) {  
  51.             // writing error to Log  
  52.             e.printStackTrace();  
  53.         }  
  54.         // Making HTTP Request  
  55.         try {  
  56.             HttpResponse response = Client.execute(Post);  
  57.             StatusLine statusLine=response.getStatusLine();  
  58.             // writing response to log  
  59.             Log.d("Http Response:", response.toString());  
  60.             Log.d("statusline:"""+statusLine);  
  61.    
  62.         } catch (ClientProtocolException e) {  
  63.             // writing exception to log  
  64.             e.printStackTrace();  
  65.         } catch (IOException e) {  
  66.             // writing exception to log  
  67.             e.printStackTrace();  
  68.         }  
  69.     }  
Step 4
 
Use the following for the Android manifest.xml file:
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     package="com.androidhttpclient"  
  4.     android:versionCode="1"  
  5.     android:versionName="1.0" >  
  6.     <uses-sdk  
  7.         android:minSdkVersion="7"  
  8.         android:targetSdkVersion="16" />  
  9.    
  10.     <application  
  11.         android:allowBackup="true"  
  12.         android:icon="@drawable/ic_launcher"  
  13.         android:label="@string/app_name"  
  14.         android:theme="@style/AppTheme" >  
  15.         <activity  
  16.             android:name="com.androidhttpclient.MainActivity"  
  17.             android:label="@string/app_name" >  
  18.             <intent-filter>  
  19.                 <action android:name="android.intent.action.MAIN" />  
  20.    
  21.                 <category android:name="android.intent.category.LAUNCHER" />  
  22.             </intent-filter>  
  23.         </activity>  
  24.     </application>  
  25. <uses-permission android:name="android.permission.INTERNET"></uses-permission>  
  26. </manifest> 
Step 5
 
The read response and statusline returned from the server-side:
 
JsonArrayData


Similar Articles