Grabbing a page using socket : HttpURLConnection « Network Protocol « Java






Grabbing a page using socket

   
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();
  }
}

   
    
    
  








Related examples in the same category

1.Get the date of a url connection
2.Get the document expiration date
3.Get the document Last-modified date
4.Show the content type
5.Show the content length
6.Display request method
7.Get response code
8.Display response message
9.Display header information
10.Download and display the content
11.A Web Page Source Viewer
12.Reading from a URLConnection
13.Use BufferedReader to read content from a URL
14.Check if a page exists
15.Identify ourself to a proxy
16.Connect through a Proxy
17.Preventing Automatic Redirects in a HTTP Connection
18.Converting x-www-form-urlencoded Data
19.Getting the Cookies from an HTTP Connection
20.Sending a Cookie to an HTTP Server
21.Getting the Response Headers from an HTTP Connection
22.java.net.Authenticator can be used to send the credentials when needed
23.Http Header Helper
24.Http connection Utilities
25.Available Port Finder