HTTP in Android

Introduction

This article explains HTTP in Android.

What is HTTP

HTTP stands for HyperText Transfer Protocol. It is used for communication between the client and server. HTTP works as a request/response protocol between a client and a server. In this protocol a client requests information from the server, then the server returns a response to the client. The response contains the information about the status and sometimes maybe the content.

HTTP provides two request methods, Get and Post.

Get: Requests data from the server.

Post: Submits data to the server.

Android has two HTTP clients, one is HttpUrlConnection and the other is HttpClient. A HTTP client is used when we want to send data to and receive data from the internet. The Get and Post methods are the basic methods to exchange information with the  server. Suppose I want to send some text data to the server. So the first step is create a default HTTP client to send the data.

HttpClient httpClient=new DefaultHttpClient();

After creating the HttpCLient we will instantiate a class to handle the post request and an URL as a parameter.

HttpPost httpPost=new HttpPost(url);

url is the URL that you want to invoke to send data. Now make your list that contains your data that you want to send. Then set it inside our post request to be sent so that it can be sent.

httpPost.setEntity(new UrlEncodedFormEntity(your list object);

URL encoding is used to encode the parameter that you want to send. At last we execute our request through the instance of the HTTP client and receive the response.

HttpResponse httpResponse=httpClient.execute(url);

For reading the response we can obtain an inputstream and consume it reading data in this way.

InputStream inputStream=httpResponse.getEntity().getContent();
 
getEntity(): gets the message entity of this response.
getContent(): creates the inputStream of the entity.
 
What a Stream is

A Stream is just like a stream of water that consists of a sequence of data (bytes).

InputStream

An Input Steam in Java reads data from a source; it may be a file, array and so on. Input stream is a class in Java.

This is how to write to Get and Post data: 

  1. HttpClient httpClient=new DefaultHttpClient();  
  2. HttpPost httpPost=new HttpPost(url);  
  3. httpPost.setEntity(new UrlEncodedFormEntity(your list object);  
  4. HttpResponse httpResponse=httpClient.execute(url);  
  5. InputStream inputStream=httpResponse.getEntity().getContent();  
  6. BufferedReader reader=new BufferedReader(new InputStreamReader(inputStream));  
  7.   
  8. StringBuilder stringBuilder=new StringBuilder();  
  9. String line=null;  
  10. while(line=reader.readLine())  
  11. {  
  12.        stringBuilder.append(line+"\n");  
  13.         
  14. }  
  15. inputStream.close();  

Step 1

Create an XML file with the following:

  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.    
  6.     <TextView  
  7.         android:id="@+id/txtView"  
  8.         android:layout_width="wrap_content"  
  9.         android:layout_height="wrap_content"  
  10.         android:layout_alignParentTop="true"  
  11.         android:layout_centerHorizontal="true"  
  12.         android:layout_marginTop="20dp"  
  13.         android:text="Enter Something Below:"  
  14.         android:textAppearance="?android:attr/textAppearanceLarge" />  
  15.    
  16.     <EditText  
  17.         android:id="@+id/edtText1"  
  18.         android:layout_width="wrap_content"  
  19.         android:layout_height="wrap_content"  
  20.         android:layout_below="@+id/textView1"  
  21.         android:layout_centerHorizontal="true"  
  22.         android:layout_marginTop="30dp"  
  23.         android:ems="10"  
  24.         android:hint=""  
  25.         >  
  26.    
  27.         <requestFocus />  
  28.     </EditText>  
  29.    
  30.     <ProgressBar  
  31.         android:id="@+id/progressBar1"  
  32.         style="?android:attr/progressBarStyleLarge"  
  33.         android:layout_width="wrap_content"  
  34.         android:layout_height="wrap_content"  
  35.         android:layout_below="@+id/editText1"  
  36.         android:layout_centerHorizontal="true"  
  37.         android:layout_marginTop="24dp" />  
  38.    
  39.     <Button  
  40.         android:id="@+id/btn_send"  
  41.         android:layout_width="wrap_content"  
  42.         android:layout_height="wrap_content"  
  43.         android:layout_alignLeft="@+id/textView1"  
  44.         android:layout_alignRight="@+id/editText1"  
  45.         android:layout_below="@+id/progressBar1"  
  46.         android:layout_marginTop="24dp"  
  47.         android:text="Submit" />  
  48.    
  49. </RelativeLayout>  

Step 2

Create a Java class file with the following:  

  1. package com.example.locationapp;  
  2.    
  3. import java.io.IOException;  
  4. import java.util.ArrayList;  
  5. import java.util.List;  
  6. import org.apache.http.HttpResponse;  
  7. import org.apache.http.NameValuePair;  
  8. import org.apache.http.client.ClientProtocolException;  
  9. import org.apache.http.client.HttpClient;  
  10. import org.apache.http.client.entity.UrlEncodedFormEntity;  
  11. import org.apache.http.client.methods.HttpPost;  
  12. import org.apache.http.impl.client.DefaultHttpClient;  
  13. import org.apache.http.message.BasicNameValuePair;  
  14. import android.app.Activity;  
  15. import android.opengl.Visibility;  
  16. import android.os.AsyncTask;  
  17. import android.os.Bundle;  
  18. import android.view.Menu;  
  19. import android.view.View;  
  20. import android.view.View.OnClickListener;  
  21. import android.widget.Button;  
  22. import android.widget.EditText;  
  23. import android.widget.ProgressBar;  
  24. import android.widget.TextView;  
  25. import android.widget.Toast;  
  26.    
  27. public class MainActivity extends Activity implements OnClickListener{  
  28.    
  29.        private EditText edtText;  
  30.        private Button btn_send;  
  31.        private ProgressBar progressbar;  
  32.        @Override  
  33.        public void onCreate(Bundle savedInstanceState) {  
  34.               super.onCreate(savedInstanceState);  
  35.               setContentView(R.layout.activity_main);  
  36.               edtText=(EditText)findViewById(R.id.edtText1);  
  37.               btn_send=(Button)findViewById(R.id.btn_send);  
  38.               progressbar=(ProgressBar)findViewById(R.id.progressBar1);  
  39.               progressbar.setVisibility(View.GONE);  
  40.    
  41.               btn_send.setOnClickListener(new OnClickListener() {  
  42.    
  43.                      @Override  
  44.                      public void onClick(View arg0) {  
  45.                            // TODO Auto-generated method stub  
  46.                                                        // TODO Auto-generated method stub  
  47.                                          if(edtText.getText().toString().length()<1){  
  48.    
  49.                                                 // out of range  
  50.                                          }else{  
  51.                                                 progressbar.setVisibility(View.VISIBLE);  
  52.                                                 new NewAsyncTask().execute(edtText.getText().toString());               
  53.                                          }  
  54.                      }  
  55.               });     
  56.        }  
  57.    
  58.        @Override  
  59.        public boolean onCreateOptionsMenu(Menu menu) {  
  60.               getMenuInflater().inflate(R.menu.main, menu);  
  61.               return true;  
  62.        }  
  63.    
  64.        private class NewAsyncTask extends AsyncTask<String, Integer, Double>{  
  65.    
  66.               @Override  
  67.               protected Double doInBackground(String... params) {  
  68.                      // TODO Auto-generated method stub  
  69.                      Datapost(params[0]);  
  70.                      return null;  
  71.               }  
  72.    
  73.               protected void onPostExecute(Double result){  
  74.                      progressbar.setVisibility(View.GONE);  
  75.                      Toast.makeText(getApplicationContext(), "command sent", Toast.LENGTH_LONG).show();  
  76.               }  
  77.               protected void onProgressUpdate(Integer... progress){  
  78.                      progressbar.setProgress(progress[0]);  
  79.               }  
  80.    
  81.               public void Datapost(String value) {  
  82.                      // Create a new HttpClient and Post Header  
  83.                      HttpClient httpclient = new DefaultHttpClient();  
  84.                      HttpPost httppost = new HttpPost("http://somewebsite.com/receiver.php");  
  85.    
  86.                      try {  
  87.                            // Add your data  
  88.                            List<NameValuePair> ValuePairs = new ArrayList<NameValuePair>();  
  89.                            ValuePairs.add(new BasicNameValuePair("myHttpData", value));  
  90.                            httppost.setEntity(new UrlEncodedFormEntity(ValuePairs));  
  91.    
  92.                            // Execute HTTP Post Request  
  93.                            HttpResponse res = httpclient.execute(httppost);  
  94.    
  95.                      } catch (ClientProtocolException e) {  
  96.                            // TODO Auto-generated catch block  
  97.                      } catch (IOException e) {  
  98.                            // TODO Auto-generated catch block  
  99.                      }  
  100.               }  
  101.        }  
  102.        @Override  
  103.        public void onClick(View v) {  
  104.               // TODO Auto-generated method stub  
  105.    
  106.        }  
  107. }  

Step 3

Give internet permission to the Android Manifest.xml file as in the following:

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     package="com.example.locationapp"  
  4.     android:versionCode="1"  
  5.     android:versionName="1.0" >  
  6.    
  7.     <uses-sdk  
  8.         android:minSdkVersion="8"  
  9.         android:targetSdkVersion="18" />       
  10.      <uses-permission android:name="android.permission.INTERNET" />  
  11.     <application  
  12.         android:allowBackup="true"  
  13.         android:icon="@drawable/ic_launcher"  
  14.         android:label="@string/app_name"  
  15.         android:theme="@style/AppTheme" >  
  16.         <activity  
  17.             android:name="com.example.locationapp.MainActivity"  
  18.             android:label="@string/app_name" >  
  19.             <intent-filter>  
  20.                 <action android:name="android.intent.action.MAIN" />  
  21.                 <category android:name="android.intent.category.LAUNCHER" />  
  22.             </intent-filter>  
  23.         </activity>  
  24.     </application>  
  25. </manifest>  

Step 4

Enter the string you want to send:

http1
 
Step 5

Click on the button.

http2

Up Next
    Ebook Download
    View all
    Learn
    View all