java11中的http处理post请求

bihw5rsg  于 2021-07-09  发布在  Java
关注(0)|答案(2)|浏览(516)

我在使用Java11嵌入式库java.net处理post请求时遇到了一个问题。
客户端:我有两种方法 QueryGenerator 班级:

public String postTeachers(String newTeachersList) {
    this.customRequest = HttpRequest.newBuilder()
            .uri(URI.create("http://" + serverIPport + "/" + postTeachers))
            .POST(HttpRequest.BodyPublishers.ofString(newTeachersList))
            .build();
    return getResponseResults();
}

它用于创建post请求。
而且我还有一个 getResponseResults() 方法

private String getResponseResults() {

    String result = null;
    try {
        CompletableFuture<HttpResponse<String>> response = CustomHttpClientSingleton.getInstance().sendAsync(customRequest, HttpResponse.BodyHandlers.ofString());
        result = response.thenApply(HttpResponse::body).join();
    } catch(RuntimeException e) {
        System.out.println("Seems like the server may not be working properly! Restart it");
    }
    return result;
}

服务器端:我有一个方法 handlePostRequest ```
private void handlePostRequest(HttpExchange httpExchange) throws IOException {
Headers headers = httpExchange.getResponseHeaders();
httpExchange.sendResponseHeaders(200, 0);
InputStream is = httpExchange.getRequestBody();
System.out.println(is.toString());
is.close();
}

我在httpserver中得到post请求,但是当我试图显示请求主体的内容时,我没有得到任何信息。我希望收到我的arraylist集合的json表示,但我得到的唯一输出是: `sun.net.httpserver.FixedLengthInputStream` 有没有办法在post请求中获取http客户端发送的请求体,并通过Java11Java.net嵌入式库在服务器端使用它。
谢谢大家!
cdmah0mi

cdmah0mi1#

看起来您没有正确读取输入流。尝试读取输入流,而不是对其调用tostring()。请检查如何在服务器端获取作为java字符串的http post请求正文?更多信息。

f2uvfpb9

f2uvfpb92#

你必须阅读 Inputstream 内容,而不仅仅是应用 toString() .
看到了吗https://www.baeldung.com/convert-input-stream-to-string

相关问题