2014/04/28

program ExHTTPClient

Contoh program aplikasi HTTP Client yang akan menggunakan perintah HTTP untuk mengambil dokumen yang ada melalui protokol HTTP
import java.io.*;
import java.net.*;
/**
* Contoh aplikasi yang membuka koneksi ke web server
* local dan membaca sebuah dokument darinya
*/
public class ExHTTPClient{
public static void main(String args[])
{
try
{
//Buka koneksi client dengan socket
Socket clientSocket = new Socket(args[0],80);
System.out.println("Client:"+ clientSocket);
//Panggil method untuk mengambil dokumen
getHTML(clientSocket,args[1]);
}
catch(UnknownHostException e)
{ System.out.println(e);}
catch(IOException e)
{ System.err.println(e);}
}
/**
* Method yang akan meminta sebuah dokumen ke web server.
* Tampilkan hasil reply dari server dan tutup
* koneksinya.
*/
public static void getHTML(Socket clientSocket,
String fileName)
{
try
{
// membentuk input dan output stream dari
// socket yang terbentuk untuk pengiriman
// dan penerimaan data
DataOutputStream outbound = new DataOutputStream(
clientSocket.getOutputStream());
DataInputStream inbound = new DataInputStream(
clientSocket.getInputStream());
//kirim sebuah permintaan HTTP ke server
outbound.writeBytes("GET" + fileName +
"HTTP/1.0\r\n\r\n");
//membuat respone dari HTTP
String responseLine;
while((responseLine = inbound.readLine())
!=null)
{
//tampilkan setiap baris ke layar monitor
System.out.println(responseLine);
}
//Clean up
outbound.close();
inbound.close();
clientSocket.close();
}
catch (IOException e)
{ System.out.println(e);}
}
}

HASIL PROGRAM:
klik ctrl + 1 , lalu akan muncul tool output (dalam bentuk pesan) seperti berikut:


setelah itu, klik ctrl + 2, lalu akan muncul pesan CMD seperti berikut:
 

Contoh Output :

Client :

Socket[addr=localhost/127.0.0.1,port=80,localport=1072]

HTTP/1.1 200 OK

Date : Tue,20 Sep 2005 02:15:38 GMT

Server: Apache/1.3.23 (Win32)

Last-Modified : Tue, 05 Aug 2003 17:00:00 GMT

Etag : “0-74d-3f2fe290”

Accept-Ranges : bytes

Content-Length : 1869

Connection : close

Content-Type : text/html
<html> ..... dan seterusnya