java - 从 POST 请求中读取正文

标签 java http

我的任务是编写一个简单的 HTTP 客户端和服务器,后者将一些 JSON 对象发送到服务器。我决定使用 unirest ,不幸的是,它的文档很少,但相当容易使用。 整个过程几乎按预期工作,除了一件事 - 服务器不从 POST 方法读取正文,仅读取 header 。发送不同大小的消息会导致 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

最佳答案

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

while (!line.isEmpty()) {

BufferedReader 的文档说它在流的末尾返回 null,而不是空字符串。

关于java - 从 POST 请求中读取正文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49374247/

相关文章:

ajax - 通过 http 流式传输二进制数据

java - 范围问题。引用方法如何?

java.lang.NoSuchMethodError : org. mockito.Mockito.framework()Lorg/mockito/MockitoFramework

http - WebLogic 为空的主机 header 请求返回 Bad Request

android - Ionic2: Http 发送 {"isTrusted":true} - 与其他可观察对象冲突?

http - Cneonction 和 nnCoection HTTP header

python: urllib.request.urlopen 不起作用

java - 更新与桥表连接的表的元素

java - JFrame组件: "Drag-Bar"?

java - 删除类(class)时无法删除时段