I am trying to send a post request, but springboot doesnt seem to recieve it. My code:
Serverside reader
@RestController
public class MessageService {
@PostMapping(path = "/online")
public ResponseEntity<?> getResponse(){
System.out.println("Post Recieved");
return new ResponseEntity<>(HttpStatus.OK);
}
}
Client
private String url = "http://127.0.0.1:8090";
public static void main(String[] args) throws IOException {
SpringApplication.run(Client.class, args);
new StartupService().init();
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
StartupService/ POST Sender
public void init() throws IOException {
String query = "Body";
Client client = new Client();
HttpURLConnection urlConn;
URL mUrl = new URL(client.getUrl() "/online");
urlConn = (HttpURLConnection) mUrl.openConnection();
//query is body
urlConn.addRequestProperty("Content-Type", "application/" "POST");
urlConn.setDoOutput(true);
urlConn.setRequestProperty("Content-Length", Integer.toString(query.length()));
urlConn.getOutputStream().write(query.getBytes(StandardCharsets.UTF_8));
System.out.println("Post Sent");
}
I tried sending a POST request via Postman, which worked as expected and gave me the console output. But the POST from code isn't recieved from the server.
CodePudding user response:
FIXED: I used a simpler method to send a POST:
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(userClient.getUrl() "/online"))
.POST(HttpRequest.BodyPublishers.ofString(query))
.build();
HttpResponse<String> response = client.send(request,
HttpResponse.BodyHandlers.ofString());
System.out.println(response.body());
System.out.println("Post Sent");