Android Networking - Using Java Networking API

In earlier tutorial we have learn about the Apache HttpClient library to perform network operations. Except Apache HttpClient library android also allows accessing the network resources via the Java networking API (java.net package). In this tutorial we will learn about how to use standard Java networking API to make simple HTTP connection in Android.

In Java Networking API below are the packages useful for network connections.
  • java.net.URL
  • java.net.URLConnection
Below are the code snippets to make a simple HTTP connection using Java networking API.

1. First create the URL instance specify the location of the resource on the internet.
URL url=new URL(“http://www.androidaspect.com”);

2. Then use the URLConnection class for reading or writing (Instances of URLConnection class can be used both to read from and to write to the resource referenced by the URL).
URLConnection conn = url.openConnection();

3. Then read the response received.
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line = "";
            while ((line = rd.readLine()) != null) {
            System.out.println(line);
            }

Note: To perform the network operations you must add the permission "android.permission.INTERNET" to "AndroidManifest.xml" file.


Final Code



The following is the final code to make a simple HTTP connection using standard Java networking API.

Project Name : JavaNetAPI
Package : com.sunil.javanetapi 
Main Activity : MainActivity.java
Layout : main.xml
Build Target : Android 2.2

AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.sunil.javanetapi"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="5"
        android:targetSdkVersion="8" />

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

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.sunil.javanetapi.MainActivity"
            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>

main.xml
<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:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginBottom="10dip"
        android:layout_marginTop="10dip"
        android:text="R E S U L T" />

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="fill_parent" >


        <TextView
            android:id="@+id/tvResult"
            android:layout_width="match_parent"
            android:layout_height="fill_parent"
            android:text="" />
       
    </ScrollView>

</LinearLayout>

MainActivity.java
package com.sunil.javanetapi;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;


public class MainActivity extends Activity {

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        TextView result = (TextView) findViewById(R.id.tvResult);

        try {

            //Java Networking API
            URL url = new URL("http://www.androidaspect.com");
            URLConnection conn = url.openConnection();

            //Read the Response
            BufferedReader rd = new BufferedReader(new
                    InputStreamReader(conn.getInputStream()));
            String line = "";
            while ((line = rd.readLine()) != null) {
                result.append(line);
            }
        } catch (Exception exe) {
            exe.printStackTrace();

        }
    }
}

Output



That's it ! You can also download the source code of this tutorial. 

Download Code






Be the first to comment

Post a Comment

Recent Posts

Site Stats

Our Apps

Get it on Google Play

©2012-2014 AndroidAspect - All rights reserved | diwali greetings | Powered by Blogger

Creative Commons License