【问题标题】:Can you include raw JSON in Guzzle POST Body?你可以在 Guzzle POST Body 中包含原始 JSON 吗?
【发布时间】:2015-09-14 06:30:59
【问题描述】:

这应该很简单,但我已经花了几个小时寻找答案并且真的被卡住了。我正在构建一个基本的 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();

【问题讨论】:

  • 大家好。感谢您的快速回复。我最终意识到我是一个智障,并且将标题和正文放在单独的数组中。将其更改为: [ 'headers' => $headers ], [ 'body' => $GetOrder ] 改为: [ 'headers' => $headers, 'body' => $GetOrder ]
  • 即便如此,您也可以使用“json”选项,如我的回答所示;它简化了一些事情。
  • 谢谢杰克。这是一个有用的答案,但我有很多调用很长的 JSON 查询,我不想将它们全部转换为 PHP 以使用 json 函数
  • 不知道为什么要自己构建 JSON 字符串,这似乎适得其反。

标签: php json curl guzzle


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    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 之前,输出没有被格式化。

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

        猜你喜欢
        • 2016-12-24
        • 1970-01-01
        • 2019-01-14
        • 1970-01-01
        • 2019-02-20
        • 2018-09-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多