Home > Pemrograman Java, Sistem Terdistribusi > Membaca Halaman Web per Byte dengan URLConnection

Membaca Halaman Web per Byte dengan URLConnection


Pada dasarnya, stream atau aliran data di jaringan dibaca byte demi byte (karakter demi karakter, satu karakter memerlukan 1 byte memory, 8 bit).

Berikut ini adalah kode program yang dapat digunakan untuk membaca halaman web byte demi byte menggunakan kelas URLConnection:

//Download halaman web menggunakan URL & URLConnection
import java.io.BufferedInputStream;
import java.net.URL;
import java.net.URLConnection;

public class URLConnectionPage {
  public static void main(String[] args) throws Exception {
    URLConnection urlc = new URL("http://localhost").openConnection();

    BufferedInputStream buffer = new BufferedInputStream(urlc.getInputStream());

    int byteRead;
    while ((byteRead = buffer.read()) != -1){
      System.out.print((char) byteRead);
    }
    buffer.close();
  }
}

Jika anda tetap ingin membaca stream data web yang diterima baris demi baris, kode program di bawah ini dapat digunakan. Yang terjadi dibelakang layar tetap, yaitu membaca byte demi byte, perbedaan hanya dari sisi programan:

import java.net.*;
import java.io.*;

public class URLConnectionReader {
    public static void main(String[] args) throws Exception {
        URL unijoyo = new URL("http://www.trunojoyo.ac.id/");
        URLConnection yc = unijoyo.openConnection();
        BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
        String inputLine;

        while ((inputLine = in.readLine()) != null)
            System.out.println(inputLine);
        in.close();
    }
}
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: