Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.URL;

public class Main {
    public static void main(String[] args) throws Exception {
        String pageAddr = "http://www.google.com/index.htm";
        URL url = new URL(pageAddr);
        String websiteAddress = url.getHost();

        String file = url.getFile();
        Socket clientSocket = new Socket(websiteAddress, 80);

        BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));

        OutputStreamWriter outWriter = new OutputStreamWriter(clientSocket.getOutputStream());
        outWriter.write("GET " + file + " HTTP/1.0\r\n\n");
        outWriter.flush();
        BufferedWriter out = new BufferedWriter(new FileWriter(file));
        boolean more = true;
        String input;
        while (more) {
            input = inFromServer.readLine();
            if (input == null)
                more = false;
            else {
                out.write(input);
            }
        }
        out.close();
        clientSocket.close();
    }
}