简体   繁体   中英

RestTemplate for GET request with JSON payload

I'm trying to create test unit for GET method which requires JSON payload to get result based on provided data in JSON.

I have tried that:

   User user = new User();
   user.setUserId(userId);

   ResponseEntity<User> getResponse = restTemplate.exchange(getRootUrl() + "/getUser", HttpMethod.GET, user, User.class);

    assertNotNull(getResponse);
    assertEquals(getResponse.getStatusCode(), HttpStatus.OK);

but it throws an error on exchange for user that object is not suitable.

the method documentation is pretty straightforward

Execute the HTTP method to the given URI template, writing the given request entity to the request, and returns the response as ResponseEntity. URI Template variables are expanded using the given URI variables, if any.

Specified by: exchange in interface RestOperations Parameters: url - the URL method - the HTTP method (GET, POST, etc) requestEntity - the entity (headers and/or body) to write to the request may be null) responseType - the type of the return value uriVariables - the variables to expand in the template

you need change user to HttpEntity

  HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON)); JSONObject parm = new JSONObject(); parm.put("user", user); HttpEntity<JSONObject> entity = new HttpEntity<JSONObject>(parm, headers); 

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