Showing posts with label android tutorials. Show all posts
Showing posts with label android tutorials. Show all posts

HTTP post from an android application using URLConnection



A simple android application which makes a HTTP POST request to a servlet.

The comments in the source are quite self explanatory. Leave a feedback for any clarifications.


SDK version used : 2.3.3

The project structure :







1. AndroidManifest.xml





<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

    package="com.httpapp"

    android:versionCode="1"

    android:versionName="1.0" >



    <uses-sdk android:minSdkVersion="10" />

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



    <application

        android:icon="@drawable/ic_launcher"

        android:label="@string/app_name" >

        <activity

            android:name=".HttpAppActivity"

            android:label="@string/app_name" >

            <intent-filter>

                <action android:name="android.intent.action.MAIN" />



                <category android:name="android.intent.category.LAUNCHER" />

            </intent-filter>

        </activity>

    </application>



</manifest>





We have to add the permission for internet access.


2. main.xml


This is your layout for your main activity



<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:layout_width="fill_parent"

    android:layout_height="fill_parent"

    android:orientation="vertical" >





    <TextView

        android:id="@+id/textView1"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="@string/firstname"

        android:textAppearance="?android:attr/textAppearanceLarge" />







    <EditText

        android:id="@+id/fnameID"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:ems="10" />





    <TextView

        android:id="@+id/textView4"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="@string/lastname"

        android:textAppearance="?android:attr/textAppearanceLarge" />





    <EditText

        android:id="@+id/lnameID"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:ems="10" >



        <requestFocus />

    </EditText>



    <Button

        android:id="@+id/submitID"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="@string/submit" />







    <TextView

        android:id="@+id/resultID"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:layout_weight="0.41" />



</LinearLayout>




3. strings.xml


<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="hello">Hello World</string>
    <string name="app_name">HTTP app</string>
    <string name="submit">submit</string>
    <string name="firstname">First name</string>
    <string name="lastname">Last name</string>

</resources>



4. HttpAppActivity.java






package com.httpapp;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class HttpAppActivity extends Activity {
    
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        // Get the submit button and attach a listener to its click event
        Button submitBtn = (Button)findViewById(R.id.submitID);
        submitBtn.setOnClickListener(new Button.OnClickListener(){

            public void onClick(View v)
            {
           
            EditText fnameText = (EditText)findViewById(R.id.fnameID); // Get a handle to the input box for first name
            EditText lnameText = (EditText)findViewById(R.id.lnameID); // Get a handle to the input box for last name
           
           
           
            //Make a call to our helper class
            String result = ServletInterface.executeHttpRequest(fnameText.getText().toString(), lnameText.getText().toString());
           
           
           
            TextView resultView = (TextView) findViewById(R.id.resultID); // Get the textView where we will display the result
            resultView.setText(result); //set the returned result to the view
            }
        });
            
    }

}




5. ServletInterface.java







package com.httpapp;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;

import android.util.Log;

/**
*  This class is the interface for making calls to a Servlet in a remote server
*
*/
public class ServletInterface 
{
public static final String SERVER_URL = "http://10.0.2.2:8080"; // The server(Servlet) which will process the request. Note 10.0.2.2 is the localhost IP for emulator
    public static final String CHAR_SET = "UTF-8"; // Encoding used for the parameters

  
    
    public static String executeHttpRequest(String fname, String lname) 
    {
   
    OutputStream output = null;
    String response = ""; 
   
    try 
    {
    Log.i("HTTP :", "Preparing data");
    // ------------------------------------------------------START: PREPARE CONNETION AND REQUEST ------------------------------- //
   
    // Prepare the data string  [ firstName=JOHN&lastName=SMITH ]
String data = URLEncoder.encode("firstName", CHAR_SET) + "=" + URLEncoder.encode(fname, CHAR_SET);
data += "&" + URLEncoder.encode("lastName", CHAR_SET) + "=" + URLEncoder.encode(lname, CHAR_SET);
URLConnection connection = new URL(SERVER_URL).openConnection(); // Create a connection to server using URL
connection.setDoOutput(true); // This means POST method to be used
connection.setRequestProperty("Accept-Charset", CHAR_SET); //For servers to know what encoding is used for the parameters
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + CHAR_SET);
output = null; 
output = connection.getOutputStream(); //open a Output stream from the connection for posting data
   output.write(data.getBytes(CHAR_SET)); //Post data
   
   //------------------------------------------------------ END: PREPARE CONNETION AND REQUEST --------------------------------- //
   
   
   Log.i("HTTP :", "sending data");
   InputStream responseStream = connection.getInputStream(); //This is when the request is actually fired
   
   
   
 //------------------------------------------------------ START: READ RESPONSE ------------------------------------------------ //
   
   Log.i("HTTP :", "Reading response");
            BufferedReader rd = new BufferedReader(new InputStreamReader(responseStream,CHAR_SET)); // Connect a BufferReader to the inputStream
            String line = null;
            
            while ((line = rd.readLine()) != null) // Read the response line-by-line from the bufferedReader
            {
               response += line;
            }
   
 //------------------------------------------------------ END: READ RESPONSE ------------------------------------------------- //
   
   

}
    catch (UnsupportedEncodingException e) 
    {
e.printStackTrace();
}
    catch(IOException io)
    {
    //Log and check exp
    }
    finally
    {
    if (output != null) try { output.close(); } catch (IOException ignoreIO) {}
    }
   
   
return response;
   
    }
}




= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =


At the servlet end you can read the parameters using :



String fname = (String) request.getParameter("firstName");

String lname = (String) request.getParameter("lastName");

       







Android's strings.xml







It is located at res/values/strings.xml


A common place for strings constants. The purpose of this file is to move the string values out of the xml files. 






<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="hello">Hello World</string>
    <string name="app_name">My app name</string>
    <string name="Name">name</string>
    <string name="submit">submit</string>

</resources>









Example 1: manifest.xml



<application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >



The @string/app_name is the application name which is coming from the strings.xml



Example 2: main.xml (layouts)


<TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/Name" />

The @string/Name value at this TextView component is coming from the strings.xml