簡體   English   中英

Spring 引導:如何將參數添加到 TestRestTemplate.postForEntity?

[英]Spring Boot: How to Add Params to TestRestTemplate.postForEntity?

我正在嘗試向postForEntity請求添加參數,但它似乎永遠不會通過 go。 這是最小的可重現代碼:

@Test
public void test()
{
    String urlTemplate = UriComponentsBuilder.fromHttpUrl("http://localhost:8080/test")
            .queryParam("update")
            // .queryParam("update", "{update}") //This does not work either
            .encode()
            .toUriString();

    HashMap<String, String> paramValues = new HashMap<>();
    paramValues.put("update", "true");

    HttpEntity<AnimateRequest> httpEntity = new HttpEntity<>(null, new HttpHeaders());

    ResponseEntity<Boolean> response = this.template.postForEntity(
            urlTemplate,
            httpEntity,
            Boolean.class,
            paramValues);
    boolean bb = response.getBody();
}

在 controller 中:

@PostMapping(value = "/test")
public ResponseEntity<Boolean> tester(@RequestParam(name="update", required = false) boolean rr)
{
    return ResponseEntity
            .ok()
            .contentType(MediaType.TEXT_PLAIN)
            .body(rr);
}

錯誤:

org.springframework.web.client.RestClientException: Error while extracting response for type [class java.lang.Boolean] and content type [application/json]; nested exception is org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize instance of `java.lang.Boolean` out of START_OBJECT token; nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `java.lang.Boolean` out of START_OBJECT token

在 [來源:(PushbackInputStream); 行:1,列:1]

首先,您必須在UriComponentsBuilder中為您的查詢參數聲明一個占位符。

String urlTemplate = UriComponentsBuilder.fromHttpUrl("http://localhost:8080/test")
            .queryParam("update", "{update}")
            .encode()
            .toUriString();

然后在RestOperations.exchange(...)調用中提供該參數的值。 它比手動連接字符串更干凈,它會為您處理 URL 編碼。

ResponseEntity<Boolean> response = this.template.exchange(
        urlTemplate,
        HttpMethod.POST,
        null,
        Boolean.class,
        paramValues);

我不確定為什么,但是需要刪除返回的 contentType()。 然后原始boolean或 class Boolean工作。

主要問題是,您的實現嘗試在沒有將任何Boolean注冊到text/plain轉換器的情況下以text/plain響應。

你有幾個選項來解決這個問題:

  1. 只需返回(響應)“默認(媒體)類型”:

     return ResponseEntity.ok().body(rr);
  2. 如果您需要以文本/純文本回復,則

    一個。 ResponseEntity<String>將是直接的解決方案:

     @PostMapping(value = "/test2") public ResponseEntity<String> // String... not Boolean... { return ResponseEntity.ok().contentType(MediaType.TEXT_PLAIN) // explicit media type here or as @PostMapping;produces attribute .body(String.valueOf(rr)); // convert the boolean here }

    灣。 或者真正注冊一個自定義(化)(布爾<->文本/純文本)轉換器......

然后我們可以測試 1.(使用 TestRestTemplate),例如:

    @Test
    public void test1() throws URISyntaxException {
      final String baseUrl = "http://localhost:" + randomServerPort + "/test/";
      URI uri = new URI(baseUrl);
      // true:
      ResponseEntity<Boolean> result = this.restTemplate.postForEntity(uri + "?update=true", null /*here goes normally the "post body"/entity*/, Boolean.class);

      assertThat(result.getStatusCodeValue()).isEqualTo(HttpStatus.OK.value());
      assertThat(result.getBody()).isTrue();
    }

和 2. 相應地使用字符串結果:

    @Test
    public void test2() throws URISyntaxException {
      final String baseUrl = "http://localhost:" + randomServerPort + "/test2/";
      URI uri = new URI(baseUrl);
      ResponseEntity<String> result = this.restTemplate.postForEntity(uri + "?update=true", null, String.class);

      assertThat(result.getStatusCodeValue()).isEqualTo(HttpStatus.OK.value());
      assertThat(Boolean.valueOf(result.getBody())).isTrue();
    }

請考慮一下,關於“內容編碼”和“如何傳遞此update參數”,我們有幾個(開箱即用)選項。

為了簡潔、簡單和不需要,我省略了任何帖子對象和標題( null ,它將 go 作為第二個方法參數),並將唯一的參數作為“URI 參數”傳遞。


還要考慮關於RestTemplate的注釋,它也可以應用於TerstRestTemplate

注意:從 5.0 開始,此 class 處於維護模式,僅接受少量更改和錯誤請求。 請考慮使用org.springframework.web.reactive.client.WebClient ,它具有更現代的 API 並支持同步、異步和流式處理方案。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM