【问题标题】:Convert cURL to Guzzle Post sending json data将 cURL 转换为 Guzzle Post 发送 json 数据
【发布时间】:2021-07-08 16:59:24
【问题描述】:

我有这个 cURL 命令,我需要使用 Guzzle 7 将其转换为 PHP。我已经研究了几天(嗯,不止几天),但进展不快。 cURL 命令使用 Simpli.fi api 在父组织下创建组织。

curl -i -X POST -H "X-App-Key: xxxx-xx-xx-xx-xxxxxx" -H "X-User-Key: xxxx-xx-xx-xx-xxxxxx" \
  -H "Content-Type: application/json" \
  -d '{
        "organization": {
          "name": "My New Organization",
          "parent_id": "5786",
          "custom_id": "<Put your organization identifier here or omit this optional field>"
        }
      }' \
  "https://app.simpli.fi/api/organizations"

我可以使用这个网站转换它,但它不使用 Guzzle:https://onlinedevtools.in/curl 这是它给我的:

include('vendor/rmccue/requests/library/Requests.php');
Requests::register_autoloader();
$headers = array(
    'X-App-Key' => 'xxxx-xx-xx-xx-xxxxxx',
    'X-User-Key' => 'xxxx-xx-xx-xx-xxxxxx',
    'Content-Type' => 'application/json'
);
$data = '{\n        "organization": {\n          "name": "My New Organization",\n          "parent_id": "5786",\n          "custom_id": "<Put your organization identifier here or omit this optional field>"\n        }\n      }';
$response = Requests::post('https://app.simpli.fi/api/organizations', $headers, $data);

除了上面的转换代码之外,这是我迄今为止尝试过的:

    public static function createOrganization()
    {
        self::init();

        $client = new Client(['debug' => true]);

        $request = $client->request('POST',
            self::$baseUrl.'/organizations', [
            'multipart' => [
                [
                    'name' => 'data',
                    'contents' => "{'organization':{'name':'Pete's Pet Pagoda','parent_id':'1052385'}}",
                ],
            ],
            'headers' => [
                'x-app-key'   => self::$appKey,
                'x-user-key'  => self::$userKey,
                'Content-Type' => 'application/json',
            ]
        ]);

        dd($response = $request->getStatusCode());
    }

我遇到了很多不同的错误,但这是最新的:

curl_setopt_array():不能将 Output 类型的流表示为 STDIO FILE*

谁能告诉我我做错了什么?有什么遗漏吗?

更新:在进一步研究此问题并与 Laracast Slack 频道上的开发人员聊天后,我了解到这是在 Windows 系统上运行时['debug' =&gt; true] 选项的错误,并在此进行了描述GITHUB页面:https://github.com/guzzle/guzzle/issues/1413 我在 Windows 10 Pro 系统上运行。我通过将调试选项更改为使用 fopen() 来纠正它,如下所示:


'debug' => fopen('php://stderr', 'w'),

我使用 PHPStorm。它建议使用“wb”来使其二进制安全。更改后,发布请求工作正常。

【问题讨论】:

  • 旁注:{'organization':{'name':'Pete's Pet Pagoda','parent_id':'1052385'}} 不是有效的 JSON。 JSON 需要为键和字符串值加上双引号。
  • 我已经更改了上面答案中的json,因为它是错误的

标签: php curl guzzle


【解决方案1】:

您需要使用body,而不是multipart。你也可以使用json

$request = $client->request('POST',
            self::$baseUrl.'/organizations', [
            'headers' => [
                'x-app-key'   => self::$appKey,
                'x-user-key'  => self::$userKey,
                'Content-Type' => 'application/json',
            ],
            'body' => [
                '{"organization":
                      [
                          {
                              "name":"Pete`s Pet Pagoda",
                              "parent_id":"1052385"
      
                          }
                      ]
                 }',
            ],
        ]);

方法2

您可以将数组传递给 json 请求选项,它会在发送 guzzle 请求时将其转换为 json。无需将 header 用作 application/json,因为它在内部应用。

$client->request('POST',
            self::$baseUrl.'/organizations', [
            'headers' => [
                'x-app-key'   => self::$appKey,
                'x-user-key'  => self::$userKey,
                'Content-Type' => 'application/json',
            ],
            'json' => [
                "organization" => [
                         [
                             "name" => "Pete`s Pet Pagoda"
                             "parent_id" => "1052385"
                         ]
                ]
            ],
        ]);

【讨论】:

  • 这仍然不是有效的 JSON。 JSON 使用双引号,而不是单引号。
  • @El_Vanja,我尝试做类似于@bhucho 的示例的事情作为$client-&gt;request() 之外的预定义关联数组,并在其上使用json_encode(),它创建了一个有效的json 字符串。我仍然收到与我原来的帖子中提到的相同的错误。
  • @GhostHunterJim 哦,我从来没有暗示这是错误的根源。只是指出它以防有人遇到这个并尝试按原样使用它。
  • @GhostHunterJim 你得到了什么错误,你删除了你正在写的多部分,你也可以用另一种方式写它
  • @bhucho - 我(或者更确切地说是)得到的错误显示在我原始帖子的底部,但我也会在这里发布,curl_setopt_array(): cannot represent a stream of type Output as a STDIO FILE*。但是,自从我上次在这里发布以来,我已经解决了这个问题。我会更新我的 OP。
【解决方案2】:

我希望这会对你有所帮助。如需进一步调试,请使用 Middleware::tap(在此处查找更多帮助 middleware+json+request

try{
    $client = new Client();
    $response = $client->request('POST', self::$baseUrl.'/organizations', 
                [
                    'headers' => [
                        'x-app-key'   => self::$appKey,
                        'x-user-key'  => self::$userKey,
                        'Content-Type' => 'application/json',
                    ],
                   'json' => [
                        'organization' => 
                        [
                            "name" => "some_name_value",
                            "parent_id" => "id_here",
                            "custom_id" => "custom id here"
                        ]
                    ]
                ]);
   $_response = json_decode($response->getBody()->getContents(), true);
}
catch(BadResponseException $e){
    $response = $e->getResponse();
    $errorArray = json_decode($response->getBody()->getContents(), true);
    
    //echo "<pre>";
    //print_r($errorArray);

    //return some message from errorarray;
}

【讨论】:

    猜你喜欢
    • 2016-03-21
    • 1970-01-01
    • 1970-01-01
    • 2013-10-30
    • 2019-06-30
    • 2018-07-18
    • 1970-01-01
    • 1970-01-01
    • 2015-11-02
    相关资源
    最近更新 更多