I am trying to post data to my api using RestTemplate, but it returns 400 bad request exception when posting. How could i fix it?
public void postDataToApi(List<String> accountIds, String myApiUrl) {
ObjectMapper mapper = new ObjectMapper();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
String accountIdsJsonList = mapper.writeValueAsString(accountIds);
HttpEntity<String> entity = new HttpEntity<String>(accountIdsJsonList, headers);
RestTemplate restTemplate = new RestTemplate();
String result = restTemplate.postForObject(myApiUrl, entity, String.class);
}
Api that i want to post data is YahooApi
https://ads-developers.yahoo.co.jp/reference/ads-search-api/v4/BudgetOrderService/get/en/
Thanks for your reading.
I guess you need to set accountIds in map. Right now you are directly posting list as json request without key. As we can see from API doc
Try this
public void postDataToApi(List<String> accountIds, String myApiUrl) {
ObjectMapper mapper = new ObjectMapper();
HttpHeaders headers = new HttpHeaders();
Map<String, Object> reqBody = new HashMap<>();
reqBody.put("accountIds", accountIds);
headers.setContentType(MediaType.APPLICATION_JSON);
String accountIdsJsonList = mapper.writeValueAsString(reqBody);
HttpEntity<String> entity = new HttpEntity<String>(accountIdsJsonList, headers);
RestTemplate restTemplate = new RestTemplate();
String result = restTemplate.postForObject(myApiUrl, entity, String.class);
}