0

I'm facing an issue with handling POST request using Java 11 embedded library java.net.

Client side: I have two methods in my QueryGenerator class:

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

It is used to create a post request.

And also I have a getResponseResults() method

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;
}

Server side: I have a method 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();
}

I get the POST Request in my HttpServer, but when I try to display the contents of a request body, I don't get any information. I'm expecting to receive JSON representation of my ArrayList collection, but the only output I get is: sun.net.httpserver.FixedLengthInputStream

Is there any way to get request body sent by http client inside POST request and use it on the server side by means of Java 11 java.net embedded library.

Thanks to everyone!

EricSchaefer
  • 25,272
  • 21
  • 67
  • 103

2 Answers2

1

You must read Inputstream content, not just apply toString().

See https://www.baeldung.com/convert-input-stream-to-string

Cedric
  • 126
  • 4
0

It looks like you are not reading input stream properly. Try to read input stream instead of calling toString() on it. Please check How to get an HTTP POST request body as a Java String at the server side? for more information.

ByerN
  • 123
  • 7