[英]How to extract values from a Spring WebTestClient JSON response for usage in subsequent requests?
在 Spring Boot 2.4.2 中,我使用WebTestClient
在我的集成測試中調用請求。
這是獲取消息列表的第一個請求:
webTestClient
.get()
.uri("/api/messages")
.headers(http -> http.setBearerAuth(token))
.exchange()
.expectStatus().isOk()
.expectHeader().contentType(APPLICATION_JSON)
.expectBody()
.jsonPath("$.length()").isEqualTo(1)
.jsonPath("$[0].id").isNumber()
.jsonPath("$[0].type").isEqualTo(4);
現在我想調用后續請求來下載特定消息。 為此,我需要已經用jsonPath("$[0].id")
檢查過的id
。
webTestClient
.get()
.uri(uriBuilder -> uriBuilder.path("/api/messages/{id}").build(extractedId))
.headers(http -> http.setBearerAuth(token))
.exchange()
.expectStatus().isOk();
我怎樣才能把這個id
提取到一個局部變量或其他地方,以便它可用於第二個請求?
你可以查看他們的官方文檔。
但是稍微擴展一下答案,最簡單的方法就是這樣
val result = webTestClient
.get()
.uri(uriBuilder -> uriBuilder.path("/api/messages/{id}").build(extractedId))
.headers(http -> http.setBearerAuth(token))
.exchange()
.expectStatus().isOk()
.returnResult();
還有一些方法可以獲取文檔中解釋的(無限)響應流,這與上面的示例非常相似。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.