从POST请求中读取正文

时间:2018-03-19 23:51:08

标签: java http

我的任务是编写一个简单的HTTP客户端和服务器,后者将一些JSON对象发送到服务器。我决定使用unirest,遗憾的是文档记录不清,但相当容易使用。 整个过程几乎按预期工作,除了一件事 - 服务器不从POST方法读取正文,只读取标题。发送不同大小的消息会导致content-length更改其值,因此客户端就可以了。服务器的http响应也很好。

我该如何解决这个问题?

服务器:

  public class SimpleHTTPServer {

    public static void main(String args[]) throws IOException {

        ServerSocket server = new ServerSocket(8080);
        System.out.println("Listening for connection on port 8080 ....");
        while (true) {
            Socket clientSocket = server.accept();
            InputStreamReader isr = new InputStreamReader(clientSocket.getInputStream());
            BufferedReader reader = new BufferedReader(isr);
            String line = reader.readLine();
            while (!line.isEmpty()) {
                System.out.println(line);
                line = reader.readLine();
            }
            String httpResponse = "HTTP/1.1 200 OK\r\n\r\n";
            clientSocket.getOutputStream().write(httpResponse.getBytes("UTF-8"));
            clientSocket.close();
        }
    }
}

客户端:

class Client {
    void send(String address, String message) {
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss");
        LocalDateTime localDate = LocalDateTime.now();
        String time = dtf.format(localDate);
        JSONObject jsonObject = new JSONObject()
                .put("time", time)
                .put("address", address)
                .put("message", message);
        try {
            HttpResponse<String> postResponse = Unirest.post("http://127.0.0.1:8080")
                    .header("Accept", "application/json")
                    .header("Content-type", "application/json")
                    .body(jsonObject)
                    .asString();
            System.out.println(postResponse.getStatus() + " " + postResponse.getStatusText());
        } catch (UnirestException e) {
            Alert alert = new Alert(Alert.AlertType.NONE, "Couldn't connect to server!", ButtonType.OK);
            alert.showAndWait();
            e.printStackTrace();
        }
    }
}

输出(在服务器端):

POST / HTTP/1.1
Accept: application/json
accept-encoding: gzip
Content-type: application/json
user-agent: unirest-java/1.3.11
Content-Length: 66
Host: 127.0.0.1:8080
Connection: Keep-Alive

1 个答案:

答案 0 :(得分:2)

我认为这条线在服务器端是错误的:

elf

while (!line.isEmpty()) { 的文档说它在流的末尾返回BufferedReader,而不是空字符串。