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!