简体   繁体   中英

Spring boot rest template get user by id gives RestClientException error

I'm running unit test for resttemplate getuserbyid. However it returns RestClientException error Can someone please help?

Below is the resttemplate GET call

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;
    }

Below is the unit test case:

@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));
    }

Below is the user class

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

Below is the user controller class where I'm trying to make rest call to:

@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;
    }
}

Below is the error:

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)

Actually the Jackson Parser is not able to convert the response to your User class since their is skeleton difference between the two.

How about Trying below steps

  1. Try Making direct request to controller from postman and check the returned JSON matches the USER DTO.
  2. If JSON structure is perfect then try using restTemplate.getForObject()

If still things don't work post SS for your returned JSON and getForObject method

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM