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

时间:2015-06-27 10:41:14

标签: php json curl guzzle

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

我正在尝试创建一个正常工作的Guzzle客户端,但服务器正在使用'无效请求'我只是想知道我发布的JSON是否有些可疑。我开始怀疑你是否不能在Guzzle POST请求体中使用原始JSON?我知道标头正在工作,因为我从服务器收到有效的响应,我知道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();

3 个答案:

答案 0 :(得分:19)

您可以通过'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,
]);

答案 1 :(得分:0)

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

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

答案 2 :(得分:0)

在这里开枪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,输出才被格式化。

相关问题