json - WP_remote_post how to add filters to JSON API call
问题描述
I am trying to integrate an API into my Wordpress plugin. The following PHP code successfully connects to the API and retrieves a list of Estates (the API is from a real-estate software):
$url = 'https://api.whise.eu/v1/estates/list';
$body = array(
'Filter' => array( 'languageId' => 'nl-BE'),
);
$args = array(
'headers' => array( 'Authorization' => 'Bearer ' . $token),
'body' => json_decode($body)
);
$response = wp_remote_post($url,$args);
As per the documentation (http://api.whise.eu/WebsiteDesigner.html#operation/Estates_GetEstates) it is possible to filter the results, but I haven't been able to get this to work. I don't have much experience with APIs and JSON, so I might be missing something here.
The code above still retrieves the data in English, even though I added the language filter as explained in the docs. When I replace 'body' => json_decode($body)
with 'body' => $body
, I get the following response:
{"Message":"The request entity's media type 'application/x-www-form-urlencoded' is not supported for this resource."}
Thanks!
解决方案
Just so that this question doesn't go unanswered:
- You need to add the
Content-Type
header and set it toapplication/json
. This is so the endpoint can interpret your data as a JSON string. - You also need to change
'body' => json_decode($body)
to'body' => json_encode($body)
as you want to convert your$body
array into a JSON string (see json_decode() vs json_encode()).
This is how your code should look now:
$url = 'https://api.whise.eu/v1/estates/list';
$body = array(
'Filter' => array( 'languageId' => 'nl-BE'),
);
$args = array(
'headers' => array(
'Authorization' => 'Bearer ' . $token,
'Content-Type' => 'application/json'
),
'body' => json_encode($body)
);
$response = wp_remote_post($url,$args);
推荐阅读
- javascript - 使用聚合 MongoDB 生成统计信息
- batch-file - 将 WMIC 命令的输出设置为变量 .bat
- laravel - laravel 中的模型绑定,如 ASP NET Core
- reactjs - 如何修改我的模态以便在 reactjs 中以不同的方式显示不同的项目?
- python - 使用 Scrapy 将网站中的新数据提取到现有表中
- gatling - 如何在 gatling 中找到 api 断点
- javascript - jQuery - 禁用自我并启用另一个的两个链接事件
- spring - 有没有办法在另一个项目中重用来自多个项目的黄瓜步骤?
- kotlin - Kotlin 中的 Float.isNaN“接收器类型不匹配”错误
- javascript - 忽略正则表达式中的模式中的一个词