GuzzleHttp\\Exception\\ClientException: Client error: `POST resulted in a `400 Bad Request` response:\n{"@context":"\\/api\\/contexts

GuzzleHttp\\Exception\\ClientException: Client error: `POST resulted in a `400 Bad Request` response:\n{"@context":"\\/api\\/contexts

我已经使用本教程 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 以编程方式为服务器生成正确的 post?

首先,请不要 post 敏感数据,例如患者 ID、站点 ID 或您的申请 URL。

关于您的问题... 在您的 curl 命令中,您使用参数名称 vistreason 但在您的 Guzzle 请求中,您使用 visitreason.

我已经使用 Postman 对其进行了测试,它返回了 500 服务器错误,因为字段 vistreason 不能为空。

除此之外,我还使用 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!

进行交互