简体   繁体   English

将 cURL 转换为 Guzzle Post 发送 json 数据

[英]Convert cURL to Guzzle Post sending json data

I have this cURL command that I need to convert to PHP using Guzzle 7. I've have been researching this for a few (well, more than a few) days and getting nowhere fast.我有这个 cURL 命令,我需要使用 Guzzle 7 将其转换为 PHP。我已经研究了几天(嗯,不止几天),但进展不快。 The cURL command uses the Simpli.fi api to create an organization under the parent org. 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"

I was able to convert it using this website but it doesn't use Guzzle: https://onlinedevtools.in/curl Here's what it gave me:我可以使用这个网站转换它,但它不使用 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);

Here's what I've tried so far aside from the converted code above:除了上面的转换代码之外,这是我迄今为止尝试过的:

    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());
    }

I'm getting quite a few different errors however this is the latest:我收到了很多不同的错误,但这是最新的:

curl_setopt_array(): cannot represent a stream of type Output as a STDIO FILE* curl_setopt_array():不能将 Output 类型的 stream 表示为 STDIO 文件*

Can anyone tell me what I'm doing wrong?谁能告诉我我做错了什么? Is there something missing?有什么遗漏吗?

UPDATE: After further research into this issue and chatting with a developer on the Laracast Slack channel, I've come to learn that this is a bug with the ['debug' => true] option when running on a Windows system and is described on this GITHUB page: https://github.com/guzzle/guzzle/issues/1413 I'm running on a Windows 10 Pro system.更新:在进一步研究此问题并与 Laracast Slack 频道上的开发人员聊天后,我了解到这是在 Windows 系统上运行时使用['debug' => true]选项的错误,并已描述在这个 GITHUB 页面上: https://github.com/guzzle/guzzle/issues/1413我在 Windows 10 Pro 系统上运行。 I corrected it on my end by changing the debug option to use fopen() like this:我通过将调试选项更改为使用 fopen() 来纠正它,如下所示:


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

I use PHPStorm.我使用 PHPStorm。 It suggested using the 'wb' to make it binary safe.它建议使用“wb”来使其二进制安全。 After changing it, the post requests worked fine.更改后,发布请求工作正常。

You need to use body , not multipart .您需要使用body ,而不是multipart You can also use json .您也可以使用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"
      
                          }
                      ]
                 }',
            ],
        ]);

method 2方法二

You can pass array to the json request option and it will convert it to json when sending the guzzle request.您可以将数组传递给 json 请求选项,它会在发送 guzzle 请求时将其转换为 json。 No need to use header as application/json as it applies internally.无需使用 header 作为应用程序/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"
                         ]
                ]
            ],
        ]);

I hope this will help you.我希望这能帮到您。 For further debugging use Middleware::tap(find more help here middleware+json+request )如需进一步调试,请使用 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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM