dongmu5106
2018-07-08 11:08
浏览 392
已采纳

如何通过guzzle运行cURL

First time using cURL and guzzle. This is probably a simple question but would appreciate a "helloworld" example.

This is the cURL I currently have:

curl --include --request POST \
--header "application/x-www-form-urlencoded" \
--header "X-Access-Token: ACCESS_TOKEN" \
--data-binary "grant_type=client_credentials&client_id=PUBLIC_KEY&client_secret=PRIVATE_KEY" \
'https://api.url.com/token'

And this is the guzzle code:

$client = new Client(); //GuzzleHttp\Client
$result = $client->post('https://api.url.com/token', [
    'form_params' => [
        'sample-form-data' => 'value'
    ]
]);

I'm not sure how to run the cURL command using guzzle. How would the resulting guzzle code look like?

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • douying9296 2018-07-09 10:34
    已采纳

    So here's the answer for converting cURL to Guzzle. Maybe it will help future people that need a "helloworld" like I did. This is how I ran the cURL in PHP via Guzzle:

    $client = new Client();
    $uri = 'https://api.url.com/token';
    $headers = [
        'Content-Type' => 'application/x-www-form-urlencoded',
        'X-Access-Token' => $ACCESS_TOKEN
    ];
    $body = 'grant_type=client_credentials&client_id='.$PUBLIC_KEY.'&client_secret='.$PRIVATE_KEY;
    $result = $client->request('POST', $uri, [
        'headers' => $headers,
        'body' => $body
    ]);
    
    json_decode($result->getBody()->getContents(), true);
    

    Two things that weren't intuitive was you have to designate 'application/x-www-form-urlencoded' as Content-Type. And 'data-binary' as 'body'.

    已采纳该答案
    打赏 评论
  • dongyuchen9276 2018-07-08 11:37

    You can get/see the result of your Guzzle call by calling the "getBody" function. In your case, $result->getBody()

    打赏 评论
  • douwen5951 2018-07-14 16:09

    Sorry for the late answer, I see you already found a solution yourself. While it works, it's not the Guzzle way / "best practise" to manually code your body payload like that.

    Guzzle provides a cleaner way for that, and builds the body-payload internally:

    $result = $client->post('https://api.url.com/token', [
      'headers' => ['X-Access-Token' => 'ACCESS_TOKEN'],
      'form_params' => [
        'grant_type' => 'client_credentials',
        'client_id' => 'PUBLIC_KEY',
        'client_secret' => 'PRIVATE_KEY',
      ],
    ]);
    

    Correct concatenation with ?/& aswell as adding the application/x-www-form-urlencoded is done by Guzzle automatically. This is the request that is sent off by the above code:

    POST /token HTTP/1.1
    Content-Length: 76
    User-Agent: GuzzleHttp/6.3.3 curl/7.57.0 PHP/7.2.2
    Content-Type: application/x-www-form-urlencoded
    Host: api.url.com
    X-Access-Token: ACCESS_TOKEN
    
    grant_type=client_credentials&client_id=PUBLIC_KEY&client_secret=PRIVATE_KEY
    
    打赏 评论

相关推荐 更多相似问题