I am trying to create java code to delete an item from a repository in a spring boot server using the item's ID.
My server code:
@DeleteMapping("/deleteUser/{id}")
public void deleteUser(@PathVariable Long id){
userRepository.deleteById(id);
}
Java code to connect to server:
URL url = new URL("http://localhost:1234/deleteUser");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("DELETE");
conn.setRequestProperty("Content-Type", "application/json");
For my other requests of get and post I would use the output stream to write to the server, but I am not sure the exact code to send the ID that needs to be deleted to the server
CodePudding user response:
Since id
is a path variable, you must pass it as one. For example:
http://localhost:1234/deleteUser/42
I suggest you use Spring's RestTemplate
, which offers the RestTemplate#delete(String url, Map<String, ?> uriVariables)
method:
new RestTemplate().delete("http://localhost:1234/deleteUser/{id}", Collections.singletonMap("id", 42));
CodePudding user response:
You can use WebTesClient like this :
@Autowired
protected WebTestClient webTestClient;
webTestClient.delete()
.uri("http://localhost:1234/deleteUser/{id}", YOUR_ID)
.exchange()
.expectStatus().isOk();
Don't forget to add webflux
dependency:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
<scope>test</scope>
</dependency>