php - 您可以在 Guzzle POST 正文中包含原始 JSON 吗?

标签 php json curl guzzle

这应该很简单,但我花了几个小时寻找答案并且真的卡住了。我正在构建一个基本的 Laravel 应用程序,并使用 Guzzle 来替换我目前正在发出的 CURL 请求。所有 CURL 函数都在主体中使用原始 JSON 变量。

我正在尝试创建一个可用的 Guzzle 客户端,但服务器正在响应“无效请求”,我只是想知道我发布的 JSON 是否有问题。我开始怀疑您是否不能在 Guzzle POST 请求正文中使用原始 JSON?我知道 header 正在工作,因为我从服务器收到有效响应,并且我知道 JSON 是有效的,因为它当前正在 CURL 请求中工作。所以我被卡住了:-(

如有任何帮助,我们将不胜感激。

        $headers = array(
            'NETOAPI_KEY' => env('NETO_API_KEY'),
            'Content-Type' => 'application/json',
            'Accept' => 'application/json',
            'NETOAPI_ACTION' => 'GetOrder'
        );

    // JSON Data for API post
    $GetOrder = '{
        "Filter": {
            "OrderID": "N10139",
                "OutputSelector": [
                    "OrderStatus"
                ]
        }
    }';

    $client = new client();
    $res = $client->post(env('NETO_API_URL'), [ 'headers' => $headers ], [ 'body' => $GetOrder ]);

    return $res->getBody();

最佳答案

您可以通过 'json' request option 将常规数组作为 JSON 发送;这也会自动设置正确的标题:

$headers = [
    'NETOAPI_KEY' => env('NETO_API_KEY'),
    'Accept' => 'application/json',
    'NETOAPI_ACTION' => 'GetOrder'
];

$GetOrder = [
    'Filter' => [
        'OrderID' => 'N10139',
        'OutputSelector' => ['OrderStatus'],
    ],
];

$client = new client();
$res = $client->post(env('NETO_API_URL'), [
    'headers' => $headers, 
    'json' => $GetOrder,
]);

请注意 Guzzle 适用 json_encode()没有任何幕后选择;如果您需要任何定制,建议您自己完成一些工作

$res = $client->post(env('NETO_API_URL'), [
    'headers' => $headers + ['Content-Type' => 'application/json'],
    'body' => json_encode($getOrders, ...),
]);

关于php - 您可以在 Guzzle POST 正文中包含原始 JSON 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31087814/

相关文章:

php - 将自定义列产品可见性添加到 Woocommerce 3 中的管理产品列表

php - MySQL - 无法添加外键约束 - 拉丁文/西里尔文

javascript - 自引用 Parse.com 类

javascript - Angular JS 和 Symfony2

python - Curl 到 Python 请求 - Json

PHP cURL 实时代理(流文件)

php - Highcharts 为空白

php - 尝试访问从 JSON 数据创建的数组时未定义

java - 无法再从 oracle 站点 curl JDK

php - 尽管超时和其他设置增加,MySQL 服务器已经消失