使用 RestTemplate.postForObject 调用 API 时出现 400 Bad Request

400 Bad Request when using RestTemplate.postForObject to call API

我正在尝试使用 RestTemplate post 数据到我的 api,但是当 posting 时 returns 400 错误请求异常。 我该如何解决?

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 我想要 post 数据是 YahooApi

https://ads-developers.yahoo.co.jp/reference/ads-search-api/v4/BudgetOrderService/get/en/

感谢您的阅读。

我猜你需要在地图中设置accountIds。现在,您直接将列表作为 json 请求发布,无需密钥。正如我们从 API 文档中看到的

试试这个

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

您提到的 API (yahoo) 仅接受授权请求。所以 yahoo API 只期望带有令牌的安全请求(首先生成令牌并在每个请求中发送它)或 client_id & client_secret (两者结合授权请求)。