Hey guys so I have a node.js express server that listens for requests and sends responses, Initially, I made an app that sends a request from C# and gets a 200 response, Now I need to do the same in Java, so there's a string a that I need to send to the server. Here's my code
import java.util.HashMap;
import java.util.Scanner;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.HashMap;
public class App {
public static void main(String[] args) throws Exception {
//System.out.println("Hello, World!");
var values = new HashMap<String, String>() {{
put("name", "jeff");
}};
//var objectMapper = new ObjectMapper();
// String requestBody = objectMapper
// .writeValueAsString(values);
String a = "Hi this is a test";
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("http://192.168.1.46:4046/test"))
.POST(HttpRequest.BodyPublishers.ofString(a))
.build();
HttpResponse<String> response = client.send(request,
HttpResponse.BodyHandlers.ofString());
System.out.println(response);
}
}
I saw examples where the converted the request data to a JSON using the ObjectMapper, but I wish to do it without the ObjectMapper, when I did this .POST(HttpRequest.BodyPublishers.ofString(a))
in the node.js terminal I get this {}
Is there a way to fix this? I'm not a java developer but I tried making this for someone.
Just incase if you need to see my node.js code here it is
app.post("/test", (request, response) => {
console.log("Req received");
response.send('200');
console.log(request.body)
})
OUTPUT:
Server listening at port 4046
Req received
{}
Thanks for reading! I tried searching this on other resources but I did not find anything relevant.