Web Science/Part1: Foundations of the web/Hypertext Transfer Protocol/A simple web client/script

Da Wikiversità, l'apprendimento libero.
Jump to navigation Jump to search
package demo;
/**
 * this program is written by Rene Pickhardt and in the public domain GPLv3
 * contact: http://www.rene-pickhardt.de or rene@rene-pickhardt.de
 * 
 * The purpose is to demonstrate how to build a simple Web Client on top
 * of TCP / IP. Therefor we just make a very simple HTTP GET request. 
 */
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

public class SimpleWebClient {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		try {
			// create a TCP connection on port 80
			Socket httpSocket = new Socket("studywebscience.org", 80);
			
			// following HTTP/1.0 this is a simple get request
			String getRequest = "GET /test/simple.html HTTP/1.0\r\n\r\n";
			
			// send the data of the HTTP/1.0 GET request over the wire
			OutputStream requestStream = httpSocket.getOutputStream();	
			requestStream.write(getRequest.getBytes());
			
			// retrieve the response
			BufferedInputStream responseStream = new BufferedInputStream(httpSocket.getInputStream());
			
			int tmp = -1;
			
			while ((tmp = responseStream.read())>0){
				System.out.print(""+(char) tmp);
			}
			// close the connection (socket will be closed by the server!)
			requestStream.close();
			responseStream.close();
			
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

}