繁体   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