有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java 400在使用RestTemplate时请求错误。用于调用API的postForObject

我试图使用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/

谢谢你的阅读


共 (2) 个答案

  1. # 1 楼答案

    我想您需要在地图中设置AccountID。现在,您直接将列表发布为json请求,而无需密钥。我们可以从API文档中看到 enter image description here

    试试这个

    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);
    }
    
  2. # 2 楼答案

    您提到的API(yahoo)只接受授权请求。因此,yahoo API只期望具有令牌(首先生成令牌并在每个请求中发送)或客户端id&;的安全请求;客户端密码(两者结合用于授权请求)