將網頁取得邏輯封裝於靜態方法 getPage(),提升程式碼複用性與可讀性:
public class SimpleWebClient {
public static void main(String[] args) {
try {
Socket socket = new Socket("localhost", 80);
getPage(socket);
} catch (Exception e) {
e.printStackTrace();
}
}
static void getPage(Socket socket) {
try (DataOutputStream out = new DataOutputStream(socket.getOutputStream());
DataInputStream in = new DataInputStream(socket.getInputStream())) {
out.writeBytes("GET / HTTP/1.0\r\n\r\n");
String line;
while ((line = in.readLine()) != null) {
System.out.println(line);
if (line.isEmpty()) break; // 請求頭結束
}
} catch (IOException e) {
System.err.println("讀取失敗: " + e);
}
}
}
line.isEmpty() 判斷throws IOException 由呼叫端統一處理SSLSocketFactory)HttpClient 元件此架構為後續實作 HTTP 伺服器端請求解析奠定基礎。