Logo Icon Logo
A Crowd-sourced Cookbook on Writing Great Android® Apps
GitHub logo Twitter logo OReilly Book Cover Art

Simple HTTP client functions

Author: Colin Wilcox
Published? false
FormatLanguage: WikiFormat

Problem:

How to access services over HTTP fcrom a handset application

Solution:

Android provides a number of HTTP related services that allow the interrogation over servers over an HTTP connection

Discussion:

The activity needs to have permissions to access the internet. This can be done by adding the following permission line to the project manifest file.

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

The code is then as follows:

package com.androidcookbook.simplehttp;

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

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.util.Log;

public class httpclient //extends Activity 
{
	private static final String TAG = "httpclient";
	
	httpclient ()
	{
		String url = ""; // insert your http:// URL here
		String responseString = getRequest (url);
		
		Log.i (TAG, "HTTP Response : "+ responseString);
	}
      
    public String getRequest(String aUrl)
    {
    	Log.i (TAG, "getRequest ()");
    	
    	String result = "";
        
        HttpClient client = new DefaultHttpClient();
        HttpGet request = new HttpGet(aUrl);
        try
        {
            HttpResponse response = client.execute(request);
            result = processRequest(response);
        }
        catch(Exception e)
        {
        	Log.i (TAG, "Failed! : "+e.getMessage());
        }
        
        return result;
    }


    public static String processRequest(HttpResponse aResponse)
    {
    	Log.i (TAG, "processRequest ()");
    	
    	String result = "";
        try
        {
            InputStream inStream = aResponse.getEntity().getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(inStream));
            StringBuilder str = new StringBuilder();
            
            String line = null;
            while((line = reader.readLine()) != null)
            {
                str.append(line + "\n");
            }
            inStream.close();
            
            result = str.toString();
        }
        catch(Exception e)
        {
            result = "Error : " + e.getMessage ();
        }
        return (result);
    }
}
No records found.