我正在嘗試創建代碼以使用專案的 IDjava從服務器中的存盤庫中洗掉專案。spring boot
我的服務器代碼:
@DeleteMapping("/deleteUser/{id}")
public void deleteUser(@PathVariable Long id){
userRepository.deleteById(id);
}
用于連接服務器的 Java 客戶端代碼:
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");
對于我的其他請求,get我post將使用輸出流寫入服務器,但我不確定將需要洗掉的 ID 發送到服務器的確切代碼
uj5u.com熱心網友回復:
您可以像這樣使用WebTesClient:
@Autowired
protected WebTestClient webTestClient;
webTestClient.delete()
.uri("http://localhost:1234/deleteUser/{id}", YOUR_ID)
.exchange()
.expectStatus().isOk();
不要忘記添加webflux依賴項:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
<scope>test</scope>
</dependency>
uj5u.com熱心網友回復:
由于id是路徑變數,因此您必須將其作為一個變數傳遞。例如:
http://localhost:1234/deleteUser/42
我建議你使用 Spring's RestTemplate,它提供了以下RestTemplate#delete(String url, Map<String, ?> uriVariables) 方法:
new RestTemplate().delete("http://localhost:1234/deleteUser/{id}", Collections.singletonMap("id", 42));
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/427683.html
上一篇:干了四年外包增長的只有我的年齡,我決定金三銀四放手一搏
下一篇:HTTPGET 自定義標頭
