套接字示例 - 使用簡單套接字讀取網頁

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

public class Main {

    public static void main(String[] args) throws IOException {//We don't handle Exceptions in this example 
        //Open a socket to stackoverflow.com, port 80
        Socket socket = new Socket("stackoverflow.com",80);

        //Prepare input, output stream before sending request
        OutputStream outStream = socket.getOutputStream();
        InputStream inStream = socket.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(inStream));
        PrintWriter writer = new PrintWriter(new BufferedOutputStream(outStream));

        //Send a basic HTTP header
        writer.print("GET / HTTP/1.1\nHost:stackoverflow.com\n\n");
        writer.flush();

        //Read the response
        System.out.println(readFully(reader));

        //Close the socket
        socket.close();
    }
    
    private static String readFully(Reader in) {
        StringBuilder sb = new StringBuilder();
        int BUFFER_SIZE=1024;
        char[] buffer = new char[BUFFER_SIZE]; // or some other size, 
        int charsRead = 0;
        while ( (charsRead  = rd.read(buffer, 0, BUFFER_SIZE)) != -1) {
          sb.append(buffer, 0, charsRead);
        }
    }
}

你應該得到一個以 HTTP/1.1 200 OK 開頭的響應,它表示正常的 HTTP 響應,然後是 HTTP 標題的其餘部分,接著是 HTML 表單的原始網頁。

請注意,readFully() 方法對於防止過早的 EOF 異常非常重要。網頁的最後一行可能缺少一個返回,表示行尾,然後 readLine() 會抱怨,所以必須手動讀取它或使用 Apache commons-io IOUtils 中的實用程式方法

此示例是使用套接字連線到現有資源的簡單演示,它不是訪問網頁的實用方法。如果你需要使用 Java 訪問網頁,最好使用現有的 HTTP 客戶端庫,例如 Apache 的 HTTP 客戶端Google 的 HTTP 客戶端