我正在尝试使用 Matlab 发送以下 POST 请求 webwrite :
POST https://url.to.com/hello/world
HEADERS {"API_KEY": "abc123"}
JSON PAYLOAD
{
"return_type": "hello",
"entities": ["ent1"],
"events": ["legal"],
"fields": [],
"filters": {},
"start_date": "2015-01-01 00:00:00",
"end_date": "2016-01-01 00:00:00",
"format": "csv",
"compressed": false
}
在 Matlab 中,我尝试了以下操作:
API_KEY = 'abc123';
url = 'https://url.to.com/hello/world';
options = weboptions(...
'MediaType', 'application/json', ...
'HeaderFields', {...
'API_KEY', API_KEY; ...
'Content-Type' 'application/json'});
payload.('return_type') = 'hello';
payload.('entities') = ['ent1'];
payload.('events') = ['legal'];
payload.('fields') = [];
payload.('filters') = {};
payload.('start_date') = '2015-01-01 00:00:00';
payload.('end_date') = '2016-01-01 00:00:00';
payload.('format') = 'csv';
payload.('compressed') = 'false';
response = webwrite(url, payload, options);
但是,这会返回错误:
The server returned the status 400 with message "Bad Request" in response to the request to URL
我用 Postman 尝试了上面的请求并且成功了。我还验证了我的 Matlab 头文件设置是否正确。所以它必须是我的 JSON 有效载荷部分的 Matlab 设置。那里有什么问题?
更新 1:
我注意到,当您运行 jsonencode(payload)
时,它不会返回所需的格式。此外,"[ .. ]"
被丢弃了。我认为问题从那里开始,因为请求确实无效。因此,我们需要一种在必要时合并括号的方法。
最佳答案
在另一个论坛上找到了答案。问题确实是双括号。我们需要这样设置:
payload.('entities') = {{'ent1'}};
关于Matlab webwrite 中的 JSON 负载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45587780/