简体   繁体   中英

TCP Socket HTTP GET Request Content-Length > 0 but not returning actual Content

I am trying to query a REST API service hosted on a Tomcat/Spring Boot application using a TCP Socket instead of an HTTPClient as I cannot use an HTTPClient. I am able to successfully open the Socket, send the request, and receive data from the server but there is never any body or content returned in the server response. If I use a web browser to query the same URL it works just fine. Here is the program I am using to make the request:

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

        }

    }
}

The server responds with the following data:

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

The response indicates that there should be some content based on the Content-Length, but I never actually receive the content itself. Is it possible to do this? Any advice is greatly appreciated.

You stop reading when you find an empty line. There's an empty line that separates headers from content, so you're just not reading the content.

readLine returns null when the server closes the connection. Change your loop to

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM