1

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 client 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

Harry Coder
  • 2,429
  • 2
  • 28
  • 32
  • Update `URL url = new URL("http://localhost:1234/deleteUser");` to `URL url = new URL("http://localhost:1234/deleteUser/id-to-be-deleted");` – silentsudo Feb 18 '22 at 05:24

2 Answers2

2

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>
Harry Coder
  • 2,429
  • 2
  • 28
  • 32
1

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));
Oliver
  • 1,465
  • 4
  • 17