翻译cURL请求到Guzzle



我正在尝试使用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未经授权的错误。我知道我有正确的证件。Guzzle文档中说:auth目前只在使用cURL处理程序时支持,但是计划创建一个可以与任何HTTP处理程序一起使用的替代品,这让我觉得我没有走对方向。但是根据我的理解,Guzzle默认使用cURL。

$guzzleData = [
  'auth' => [$token, 'X'],
  'allow_redirects' => true,
  'verify' => false,
];
$client = new GuzzleHttpClient();
$request = $client->get($url, $guzzleData);
$response = $request->send();

解决方案如下:

$client = new GuzzleHttpClient();
$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();

我为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'包装

最新更新