Android application and the Internet

by Goran Siric on Wednesday, November 30, 2011 12:14 AM

To allow your application to connect to the internet first you need to do is  to modify AndroidManifest.xml file to request INTERNET permission for your application.

To do this open AndroidManifest.xml file and add following line if not exists:

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


It is good to know that if you want to connect to your local web server (localhost), you must use IP address of  your computer instead of  localhost keyword or 127.0.0.1 IP address. That's it because 127.0.0.1 IP address is internally used by android emulator or your android device. 

Somewhere I found that you can use 10.0.0.2 IP adress to connect to  your local web server. I tried it but this not work for me. I think that this depends of type of web server you have installed.

Here is code of  test.aspx web page which I created for testing purposes. Page returns  information about which HTTP method is used (POST or GET), what are Query String parameters and what are form data values.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
 
public partial class test : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        String result = "";
 
        result += "HTTP METHOD:" + Request.HttpMethod;
        result += "<BR>";
 
 
        if (Request.Form.Count == 0)
        {
            result += "There is no form data<BR>";
        }
        else
        {
            result += "FORM DATA:<BR>";
 
            foreach (String key in Request.Form.AllKeys)
            {
                result += key + ": " + Request.Form[key] + "<BR>";
            }
        }
 
        if (Request.QueryString.Count == 0)
        {
            result += "There is no parameters in query string<BR>";
        }
        else
        {
            result += "QUERY STRING PARAMETERS:<BR>";
 
            foreach (String key in Request.QueryString.AllKeys)
            {
                result += key + ": " + Request.QueryString[key] + "<BR>";
            }
        }
 
 
        Response.Write(result);
        Response.End();
    }
}

Execeuted in web browser without any parameters page:

http://localhost/dotnetnuke/test.aspx

will show following result:

HTTP METHOD:GET
There is no form data
There is no parameters in query string

Notice that the page  test.aspx is on my webserver installed in dotnetnuke web application. On your system it will probably be somewhere else.

Here is the code you can use to send GET and POST http requests to the page along with some QueryString parameters and with some form data (when you use POST http request). Comments are in code so I will not explain code in more details.

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
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.net.Uri;
import android.os.Bundle;
import android.widget.TextView;
 
public class UploadDataToUrlActivity extends Activity {
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
     
        super.onCreate(savedInstanceState);
         
        setContentView(R.layout.l1_upload_data_to_url);
     
         
        // Create URI with some QueryString parameters
         
        Uri uri = new Uri.Builder()
            .scheme("http")
            .authority("192.168.0.13")
            .path("dotnetnuke/test.aspx")
            .appendQueryParameter("param1", "value1")
            .appendQueryParameter("param2", "value2")
            .build();
         
         
        try
        {
            // execute HTTP GET request
            OutputStream response = HttpRequestGet(uri);
             
            // Write output to screen
            TextView txtResponseGet = (TextView)findViewById(R.id.l1_txtResponseGet);
            txtResponseGet.setText(response.toString().replace("<BR>", "\n"));
 
        }
        catch (IOException e)
        {
            // do error handling here
        }
         
        try
        {
            // Create array list of form data
            ArrayList formData = new ArrayList();
            formData.add(new BasicNameValuePair("formData1", "formValue1"));
            formData.add(new BasicNameValuePair("formData2", "formValue2"));
             
            // execute HTTP POST request
            OutputStream response = HttpRequestPost(uri,formData);
 
            // Write output to screen
            TextView txtResponsePost = (TextView)findViewById(R.id.l1_txtResponsePost);
            txtResponsePost.setText(response.toString().replace("<BR>", "\n"));
             
        }
        catch (IOException e)
        {
            // do error handling here
        }
             
         
    }
 
    // Method for sending HTTP GET request to a web page
    public OutputStream HttpRequestGet(Uri uri) throws IOException
    {
                 
        HttpGet httpget = new HttpGet(uri.toString());
         
        HttpClient httpclient = new DefaultHttpClient();
                         
        HttpResponse response = httpclient.execute(httpget);
         
        HttpEntity httpentity = response.getEntity();
         
        if (null == httpentity)
        {
            throw(new IOException("HttpEntity is null"));
        }
         
        ByteArrayOutputStream outstream = new ByteArrayOutputStream();
        httpentity.writeTo(outstream);
             
        return outstream;
    }
 
    // Method for sending HTTP POST request to a web page
    public OutputStream HttpRequestPost(Uri uri, ArrayList formData) throws IOException
    {
                 
        HttpPost httppost = new HttpPost(uri.toString());
         
        httppost.setEntity(new UrlEncodedFormEntity(formData));
     
        HttpClient httpclient = new DefaultHttpClient();
     
        HttpResponse response = httpclient.execute(httppost);
         
        HttpEntity httpentity = response.getEntity();
         
        if (null == httpentity)
        {
            throw(new IOException("HttpEntity is null"));
        }
         
        ByteArrayOutputStream outstream = new ByteArrayOutputStream();
        httpentity.writeTo(outstream);
             
        return outstream;
    }
     
}

If everything is fine you should get following result on your device:



Author
Goran Siric

Blog about programming



If you found this useful,
you can buy me a coffe :)

By me a coffe through PayPal :)


Featured articles

AndEngine - Textures tips and tricks

What you should know abot textures before get started programming your first game.

GIMP script for creating Android icons at once

Script for creating Android icons for different screen resolutions at once. Icons can be saved using standard Android icons naming conventions and saved in appropriate folders.

Creating Android button with image and text using relative layout

Source code with examples how to use relative layout to create nice buttons with text and images in Android

Android application and the Internet

Tutorial about connecting to the web pages on the Internet from Android application, using both POST and GET web requests.