Android Program to Open an Internet Data Stream

Here is source code of the Program to Open an Internet Data Stream in Android. The program is successfully compiled and run on a Windows system using Eclipse Ide. The program output is also shown below.

Before you can access Internet resources, you need to add an INTERNET uses-permission node to
your application manifest, as shown in the following XML snippet:

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

The following shows the basic pattern for opening an Internet data stream

String myFeed = getString(R.string.my_feed);
try {
    URL url = new URL(myFeed);
    // Create a new HTTP URL connection
    URLConnection connection = url.openConnection();
    HttpURLConnection httpConnection = (HttpURLConnection)connection;
    int responseCode = httpConnection.getResponseCode();
    if (responseCode == HttpURLConnection.HTTP_OK) {
        InputStream in = httpConnection.getInputStream();
        processStream(in);
     }
}
catch (MalformedURLException e) {
    Log.d(TAG, “Malformed URL Exception.”);
}
catch (IOException e) {
    Log.d(TAG, “IO Exception.”);
}

Here is the code to download a picture from internet following the url that is provided and displaying it on an Image view using an HTTP client.

advertisement
advertisement

Main Activity

 
package com.example.internet_stream;
 
import java.io.IOException;
 
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
 
 
import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
 
public class MainActivity extends Activity {
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final Button but = (Button)findViewById(R.id.button);
 
    }
 
    public void downloadPicture(View view) {
        final ProgressDialog dialog = ProgressDialog.show(this, "Download",
                "downloading");
        dialog.show();
 
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    final Bitmap downloadedBitmap = downloadBitmap("https://www.sanfoundry.com/wp-content/uploads/2013/04/san-ecosystem_new.png");
                    final ImageView imageView = (ImageView) findViewById(R.id.imageView1);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            imageView.setImageBitmap(downloadedBitmap);
                        }
                    });
 
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    dialog.dismiss();
                }
            }
        }).start();
 
    }
 
    private Bitmap downloadBitmap(String url) throws IOException {
        //Create a new HTTP url connection
        HttpUriRequest request = new HttpGet(url.toString());
        HttpClient httpClient = new DefaultHttpClient();
        //get the rsponse
        HttpResponse response = httpClient.execute(request);
        //check for the status
        StatusLine statusLine = response.getStatusLine();
        int responseCode = statusLine.getStatusCode();
        //check for the response code
        if (responseCode == 200) {
            HttpEntity entity = response.getEntity();
            byte[] bytes = EntityUtils.toByteArray(entity);
 
            Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0,
                    bytes.length);
            return bitmap;
        } else {
            throw new IOException("Download failed, HTTP response code "
                    + responseCode + " - " + statusLine.getReasonPhrase());
        }
    }
 
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
 
}

ActivityMain.xml

Sanfoundry Certification Contest of the Month is Live. 100+ Subjects. Participate Now!
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >
 
           <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="downloadPicture"
            android:text="Click to download" 
            android:id="@+id/button"/>
 
        <ImageView
            android:id="@+id/imageView1"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:src="@drawable/ic_launcher" >
        </ImageView>
 
</RelativeLayout>

internet_stream

Sanfoundry Global Education & Learning Series – 100+ Java Android Tutorials.

advertisement
If you wish to look at all Tutorials, go to Java Android Tutorials.

If you find any mistake above, kindly email to
[email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.