簡體   English   中英

使用 RestTemplate.postForObject 調用 API 時出現 400 Bad Request

[英]400 Bad Request when using RestTemplate.postForObject to call API

我正在嘗試使用 RestTemplate 將數據發布到我的 api,但它在發布時返回 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 是 YahooApi

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

感謝您的閱讀。

我猜你需要在 map 中設置 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(雅虎)僅接受授權請求。 因此,雅虎 API 只期望使用令牌(首先生成令牌並在每個請求中發送)或 client_id 和 client_secret (兩者組合以授權請求)的安全請求。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM