大佬教程收集整理的这篇文章主要介绍了使用 RestTemplate.postForObject 调用 API 时出现 400 Bad Request,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试使用 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/
感谢您的阅读。
我猜您需要在地图中设置 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(两者结合以授权请求)的安全请求。
以上是大佬教程为你收集整理的使用 RestTemplate.postForObject 调用 API 时出现 400 Bad Request全部内容,希望文章能够帮你解决使用 RestTemplate.postForObject 调用 API 时出现 400 Bad Request所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。