JackTheKnife
JackTheKnife

Reputation: 4154

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.

Upvotes: 0

Views: 2341

Answers (1)

Steve Nash
Steve Nash

Reputation: 144

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

Upvotes: 1

Related Questions