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!

2 Answers 2

1

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

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

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.