TCP套接字HTTP GET请求内容长度> 0,但未返回实际内容

时间:2019-01-24 15:53:59

标签: java spring sockets http

我正在尝试使用TCP套接字而不是HTTPClient查询托管在Tomcat / Spring Boot应用程序上的REST API服务,因为我无法使用HTTPClient。我能够成功打开套接字,发送请求并从服务器接收数据,但是服务器响应中永远不会返回任何正文或内容。如果我使用网络浏览器来查询相同的URL,它就可以正常工作。这是我用来发出请求的程序:

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;

public class SocketClient {

    public SocketClient() {
        String hostname = "192.168.10.104";
        int port = 8080;

        try (Socket socket = new Socket(hostname, port)) {

            OutputStream output = socket.getOutputStream();
            PrintWriter writer = new PrintWriter(output, false);

            writer.println("GET /company/1 HTTP/1.1");
            writer.println("Host: " + hostname + ":" + port);
            writer.println("User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36");
            writer.println("Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8");
            writer.println("Accept-Language: en-US,en;q=0.9");
            writer.println("Accept-Encoding: gzip, deflate, br");
            writer.println("Connection: close");
            writer.println();
            writer.flush();

            InputStream input = socket.getInputStream();

            BufferedReader reader = new BufferedReader(new InputStreamReader(input));

            String line;

            while (!(line = reader.readLine()).equals("")) {
                System.out.println(line);
            }
            socket.close();
        } catch (Exception ex) {

            System.out.println("Server not found: " + ex.getMessage());

        }

    }
}

服务器响应以下数据:

HTTP/1.1 200 
Content-Type: text/html;charset=UTF-8
Content-Length: 55
Date: Thu, 24 Jan 2019 15:45:00 GMT
Connection: close

响应表明应该基于Content-Length来提供一些内容,但是我从未真正收到内容本身。是否有可能做到这一点?任何建议都将不胜感激。

1 个答案:

答案 0 :(得分:4)

找到空行时,您将停止阅读。有一条空行将标题和内容分开,因此您只是不阅读内容。

服务器关闭连接时,

readLine返回null。将循环更改为

while (!(line = reader.readLine()) == null)