【问题标题】:Translate cURL request to Guzzle将 cURL 请求翻译成 Guzzle
【发布时间】:2015-07-31 16:17:15
【问题描述】:

我正在尝试使用 Guzzle 而不是直接使用 cURL 来实现和 HTTP 请求。我如何使用 Guzzle 提出相同类型的请求?还是我应该坚持使用 cURL?

$ch = curl_init();
// Set the URL
curl_setopt($ch, CURLOPT_URL, $url);
// don't verify SSL certificate
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
// Return the contents of the response as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// Follow redirects
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
// Set up authentication
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, "$token:X");

我一直遇到 401 Unauthorized 错误。我知道我有正确的凭据。让我觉得我没有走上正轨的是 Guzzle 文档指出:目前仅在使用 cURL 处理程序时才支持身份验证,但计划创建一个可与任何 HTTP 处理程序一起使用的替代品。但据我了解,Guzzle 默认使用 cURL。

$guzzleData = [
  'auth' => [$token, 'X'],
  'allow_redirects' => true,
  'verify' => false,
];

$client = new \Guzzle\Http\Client();
$request = $client->get($url, $guzzleData);
$response = $request->send();

【问题讨论】:

  • 在 Stack Exchange 上发帖时,您可能会得到更多问题的答案,投票支持迁移。
  • 正如@carlcs 所提到的,这个问题更适合 Stack Overflow。虽然对一些 Craft 插件开发者有帮助,但它本身并不是一个 Craft 问题。
  • 不错!我能够投票两次,一次是在 Craft SE 上,现在在这里! :)

标签: guzzle


【解决方案1】:

解决办法如下:

$client = new \Guzzle\Http\Client();
$request = $client->get($url);

$request->getCurlOptions()->set(CURLOPT_SSL_VERIFYHOST, false);
$request->getCurlOptions()->set(CURLOPT_SSL_VERIFYPEER, false);
$request->getCurlOptions()->set(CURLOPT_RETURNTRANSFER, true);
$request->getCurlOptions()->set(CURLOPT_FOLLOWLOCATION, true);
$request->getCurlOptions()->set(CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
$request->getCurlOptions()->set(CURLOPT_USERPWD, "$token:X");

$response = $request->send();

【讨论】:

  • 这个答案不适用于当前的 guzzlehttp
  • 这适用于像 guzzle 3 这样的旧版本吗?
【解决方案2】:

我能够为 Guzzle6 工作的解决方案是:

$headers = array();
$headers['grant_type'] = 'client_credentials';
$headers['client_id'] = $clientid;
$headers['client_secret'] = $clientSecret;

$response = $this->client->post($urlAuth, ['form_params' => $headers]);
$output = $response->getBody()->getContents();

即标题数组必须包含在'form_params'中

【讨论】:

  • 我看不到 CURLOPT_RETURNTRANSFER 被翻译成什么
猜你喜欢
  • 2022-10-08
  • 2017-11-28
  • 1970-01-01
  • 2017-01-13
  • 2023-02-12
  • 2014-07-26
  • 1970-01-01
  • 1970-01-01
  • 2015-11-02
相关资源
最近更新 更多