可以在 Guzzle POST Body 中包含原始 JSON 吗?

Can you include raw JSON in Guzzle POST Body?

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

中的原始 JSON 变量

我正在尝试创建一个可用的 Guzzle 客户端,但服务器正在响应 'invalid request',我只是想知道我发布的 JSON 是否有问题.我开始怀疑您是否不能在 Guzzle POST 请求 body 中使用原始 JSON?我知道 headers 正在工作,因为我收到了来自服务器的有效响应,并且我知道 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();

您可能需要设置 body MIME 类型。这可以使用 setBody() 方法轻松完成。

$request = $client->post(env('NETO_API_URL'), ['headers' => $headers]);
$request->setBody($GetOrder, 'application/json');

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

$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 7 这里

下面的内容对我有用 json 输入

    $data = array(
       'customer' => '89090',
       'username' => 'app',
       'password' => 'pwd'  
    );
    $url = "http://someendpoint/API/Login";
    $client = new \GuzzleHttp\Client();
    $response = $client->post($url, [
        'headers' => ['Content-Type' => 'application/json', 'Accept' => 'application/json'],
        'body'    => json_encode($data)
    ]); 
    
    
    print_r(json_decode($response->getBody(), true));

由于某些原因,直到我在响应中使用 json_decode,输出才被格式化。