将cURL请求翻译为Guzzle [英] Translate cURL request to Guzzle

查看:66
本文介绍了将cURL请求翻译为Guzzle的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to use Guzzle instead of directly using cURL to achieve and HTTP request. How do I make this same type of request but with Guzzle? Or should I just stick to 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.

Here is how for I have got. I keep running into 401 Unauthorized error. I know I have correct credentials. What makes me think I am not on the right track is the Guzzle docs stating: auth is currently only supported when using the cURL handler, but creating a replacement that can be used with any HTTP handler is planned. But from my understanding Guzzle defaults with cURL.

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

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

推荐答案

以下是解决方案:

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

这篇关于将cURL请求翻译为Guzzle的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆