将cURL请求转换为Guzzle

时间:2015-07-31 16:17:16

标签: 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 Unauthorized错误。我知道我有正确的证件。让我觉得我没有走上正轨的原因是Guzzle文档声明: auth目前仅在使用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();

2 个答案:

答案 0 :(得分:11)

以下是解决方案:

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

答案 1 :(得分:1)

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

    if ([alertView textFieldAtIndex:0])
    {
        UITextField *textfield = [alertView textFieldAtIndex:0];
        [textfield becomeFirstResponder];
    }

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