我已使用本教程https://symfonycasts.com/screencast/api-platform构建了一个API端点。我已经从Web界面测试了API,它接受输入并存储数据。现在,我正在尝试将数据从应用程序发送到端点。
curl -X POST "https://myweblocation.app/api/emergencyvisits" -H "accept: application/ld+json" -H "Content-Type: application/json" -d "{\"externalpatientid\":\"<patient-id>\",\"externalsiteid\":\"<site-id>\",\"poscode\":20,\"dos\":\"2020-02-28T00:10:52.416Z\",\"vistreason\":\"chest hurting bad\"}"
我的代码是这样的:
$client = new Client(['verify' => 'my/pem/location.pem' ]);
$siteid = $GLOBALS['unique_installation_id'];
$body = [
'externalpatientid' => $uuid,
'externalsiteid' => $siteid,
'poscode' => $pos_code,
'dos' => $date,
'visitreason' => $reason
];
$headers = [
'content-type' => 'application/json',
'accept' => 'application/ld+json'
];
$request = new Request('POST', 'https://myweblocation.app/api/emergencyvisits', $headers, json_encode($body));
$response = $client->send($request, ['timeout' => 2]);
如何让Guzzle以编程方式向服务器发送正确的帖子?
答案 0 :(得分:2)
首先,请不要发布敏感数据,例如患者ID,站点ID或您的应用程序URL。
关于您的问题...
在curl命令中,您使用参数名称vistreason
,但在Guzzle请求中,您使用visitreason
。
我已经用Postman进行了测试,由于字段vistreason
不能为空,它返回了500 Server错误。
除此之外,我还用Guzzle(6.x)进行了测试:
$client = new Client(['verify' => false]); // I deactivated ssl verification
$body = [
'externalpatientid' => '<id from curl request>',
'externalsiteid' => '<id from curl request>',
'poscode' => 20,
'dos' => '2020-02-28T00:10:52.416Z',
'vistreason' => 'chest hurting bad'
];
$response = $client->request(
'POST',
'<your-server-api-url>',
[
'headers' => [
'content-type' => 'application/json',
'accept' => 'application/ld+json'
],
'body' => json_encode($body),
]
);
var_dump(json_decode($response->getBody()->getContents()));
// Output seems to be a valid response with some data from the request.
也许您的证书验证存在问题。
注意:我还强烈建议您以令牌形式实现身份验证,以便与您的API交互!