Tuesday, August 7, 2012

HttpClient and HttpGet for Android

org.apache.http.client.HttpClient is a Interface class for an HTTP client. HTTP clients encapsulate a smorgasbord of objects required to execute HTTP requests.

org.apache.http.client.methods.HttpGet provide HTTP GET method.



package com.AndroidHttpGet;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;

public class AndroidHttpGetActivity extends Activity {
 
 final String httpPath = "http://feeds.feedburner.com/AndroidCoding";
 
   /** Called when the activity is first created. */
   @Override
   public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.main);
      
       TextView text = (TextView)findViewById(R.id.text);
      
       HttpClient httpclient = new DefaultHttpClient();
       HttpGet httpget = new HttpGet(httpPath);
       try {

   HttpEntity httpEntity = httpclient.execute(httpget).getEntity();
   
   if (httpEntity != null){
    InputStream inputStream = httpEntity.getContent();
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
    StringBuilder stringBuilder = new StringBuilder();
      
    String line = null;
      
    while ((line = bufferedReader.readLine()) != null) {
     stringBuilder.append(line + "\n"); 
    }

    inputStream.close();
      
    text.setText(stringBuilder.toString());
   }
  } catch (ClientProtocolException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
   Toast.makeText(AndroidHttpGetActivity.this, e.toString(), Toast.LENGTH_LONG).show();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
   Toast.makeText(AndroidHttpGetActivity.this, e.toString(), Toast.LENGTH_LONG).show();
  }
   }
}


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:orientation="vertical"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent"
   >
<TextView 
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   android:text="@string/hello"
   />
<TextView 
   android:id="@+id/text"
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   />
</LinearLayout>


note: In order to access internet, uses-permission of "android.permission.INTERNET" have to be defined in AndroidManifest.xml.

No comments:

Post a Comment