簡體   English   中英

Spring 啟動 rest 模板通過 id 獲取用戶給出 RestClientException 錯誤

[英]Spring boot rest template get user by id gives RestClientException error

我正在為 resttemplate getuserbyid 運行單元測試。 但是它返回 RestClientException 錯誤有人可以幫忙嗎?

下面是 resttemplate GET 調用

public <T,R> ResponseEntity<T> sendGet(String url, HttpHeaders httpHeaders, R requestBody, Class<T> responseClass){
        //create an instance of rest template
        RestTemplate restTemplate = new RestTemplate();
        HttpEntity<R> entity = new HttpEntity<R>(requestBody, httpHeaders);
        //make an HTTP GET request with headers
        ResponseEntity<T> response = restTemplate.exchange(url, HttpMethod.GET, entity, responseClass);
        logger.info("GET response for: " + url + ": " + JsonUtil.jsonize(response));
        return response;
    }

下面是單元測試用例:

@Test
    public void testSuccessGetUserById() throws Exception{
        String baseUrl = "http://localhost:8080/users/1";

        //create headers
        HttpHeaders httpHeaders = new HttpHeaders();

        //set content type
        httpHeaders.setContentType(MediaType.APPLICATION_JSON);
        httpHeaders.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));

        HttpHandler httpHandler = new HttpHandler();
        //make an HTTP GET request with headers
        ResponseEntity<User> actual = httpHandler.sendGet(baseUrl, httpHeaders, null, User.class);

        //verify request succeed
        assertEquals(HttpStatus.OK, actual.getStatusCode());
        assertEquals(200, actual.getStatusCodeValue());
        assertNotNull(httpHeaders.getContentType());
        assertTrue(httpHeaders.getContentType().includes(MediaType.APPLICATION_JSON));
    }

下面是用戶class

@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
    private long id;
    private String name;
    private int age;
    private List<String> messages;
}

下面是用戶 controller class 我試圖讓 rest 調用:

@RestController
@RequestMapping("/users")
public class UserController {

    @GetMapping("/{userId}")
    public User getUser(@PathVariable("userId") String userId)
    {
        List<String> messages = new ArrayList<>();
        messages.add("Hi");

        User user = new User();
        user.setId(1);
        user.setName("John");
        user.setAge(22);
        user.setMessages(messages);
        return user;
    }
}

以下是錯誤:

org.springframework.web.client.RestClientException: Error while extracting response for type [class com.xyz.provisioning.xyz.dto.User] and content type [application/json]; nested exception is org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize instance of `com.xyz.provisioning.xyz.dto.User` out of START_ARRAY token; nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `com.xyz.provisioning.xyx.dto.User` out of START_ARRAY token
 at [Source: (PushbackInputStream); line: 1, column: 1]

    at org.springframework.web.client.HttpMessageConverterExtractor.extractData(HttpMessageConverterExtractor.java:120)
    at org.springframework.web.client.RestTemplate$ResponseEntityResponseExtractor.extractData(RestTemplate.java:998)
    at org.springframework.web.client.RestTemplate$ResponseEntityResponseExtractor.extractData(RestTemplate.java:981)
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:741)
    at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:674)
    at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:583)

實際上 Jackson 解析器無法將響應轉換為您的用戶 class 因為它們是兩者之間的骨架差異。

試試下面的步驟怎么樣

  1. 嘗試從 postman 直接請求 controller 並檢查返回的 JSON 是否與 USER DTO 匹配。
  2. 如果 JSON 結構是完美的然后嘗試使用 restTemplate.getForObject()

如果您返回的 JSON 和 getForObject 方法在 SS 后仍然無法正常工作

暫無
暫無

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

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