Java 中的原始 HTTP 1.1 请求实现未终止

Raw HTTP1.1 request implementaion in Java not getting terminated

我已经使用下面 link 中的代码实现了 httpClient。当 HTTP 请求的版本为 1.0 时,我能够获得 html 休息和程序终止。

https://www3.ntu.edu.sg/home/ehchua/programming/webprogramming/HTTP_Basics.html

如果我将版本更改为 1.1 ,则会打印响应,但即使在那之后程序也不会终止。请提及更改并提出更改建议。

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

public class HttpClient {
   public static void main(String[] args) throws IOException {
      // The host and port to be connected.
      String host = "www.google.com";
      int port = 80;
      // Create a TCP socket and connect to the host:port.
      Socket socket = new Socket(host, port);
      // Create the input and output streams for the network socket.
      BufferedReader in
         = new BufferedReader(
              new InputStreamReader(socket.getInputStream()));
      PrintWriter out
         = new PrintWriter(socket.getOutputStream(), true);
      // Send request to the HTTP server.
      out.println("GET /index.html HTTP/1.1");
      out.println();   // blank line separating header & body
      out.flush();
      // Read the response and display on console.
      String line;
      // readLine() returns null if server close the network socket.
      while((line = in.readLine()) != null) {
         System.out.println(line);
      }
      // Close the I/O streams.
      in.close();
      out.close();
   }
}

HTTP keepalive 在 1.1 中默认开启。因此,响应不会在流结束时终止:如果使用,它会由内容长度或分块终止。

参见 RFC 2616。如果您要实现 HTTP,则需要了解所有内容。