1

I'm trying to make a Post request using restTemplate,the problem is the API is accepting List<Users> in the body as POST Request

public class Users {

    String id;

    String name;

    String gender;

}

I've added the elements as

List<Users> userList=new ArrayList<Users>();
userList.add(new Users("1","AA","Male"));
userList.add(new Users("2","BB","Male"));
userList.add(new Users("3","CC","Female"));

AS

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> entity = new HttpEntity<>(headers);

ResponseEntity<String> response =  restTemplate.postForEntity(URL.toString(), HttpMethod.POST, entity, String.class);

Here how should I pass my userList into the request Body?

Jayendran
  • 9,638
  • 8
  • 60
  • 103
  • https://stackoverflow.com/questions/22507129/how-to-pass-list-or-string-array-to-getforobject-with-spring-resttemplate/22681537 will help you – Vinod Bokare Apr 26 '18 at 06:13

2 Answers2

1

You need to pass your data in HttpEntity.You can use ObjectMapper which is from jackson-databind lib to convert your list to json.

String userJsonList = objectMapper.writeValueAsString(userList);

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> entity = new HttpEntity<>(userJsonList, headers);

ResponseEntity<String> response =  restTemplate.postForEntity(URL.toString(), HttpMethod.POST, entity, String.class);

So basically it will pass the data as json string.

Sangam Belose
  • 4,262
  • 8
  • 26
  • 48
0

For Post request you can use "method=RequestMethod.POST" or @POST annotation with your method. And for list object please check below code. It will work.

public ResponseEntity<List<Users>> methodName(@QueryParam("id") String id){
List<Users> userList=new ArrayList<Users>();
userList.add(new Users("1","AA","Male"));
userList.add(new Users("2","BB","Male"));
userList.add(new Users("3","CC","Female"));

return new ResponseEntity<List<Users>>(userList, HttpStatus.OK);
}