简体   繁体   中英

400 Bad Request when using RestTemplate.postForObject to call API

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

The API (yahoo) you have mentioned is accepting only authorized requests. So yahoo API is expecting only the secure requests with either token (generate token first & send it in each reqest) or client_id & client_secret (both in combination to authorize request).

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