如何在 PHP 中的 cURL POST HTTP 请求中包含 Authorization 标头? [英] How to include Authorization header in cURL POST HTTP Request in PHP?
问题描述
我正在尝试通过 Gmails OAuth 2.0 访问用户的邮件,我正在通过 Google 的 OAuth 2.0 Playground 解决这个问题
I'm trying to access mails of a user through Gmails OAuth 2.0, and I'm figuring this out through Google's OAuth 2.0 Playground
在这里,他们指定我需要将此作为 HTTP 请求发送:
Here, they've specified I need to send this as a HTTP REQUEST:
POST /mail/feed/atom/ HTTP/1.1
Host: mail.google.com
Content-length: 0
Content-type: application/json
Authorization: OAuth SomeHugeOAuthaccess_tokenThatIReceivedAsAString
我尝试编写代码来发送此请求,如下所示:
I've tried writing a code to send this REQUEST like this:
$crl = curl_init();
$header[] = 'Content-length: 0
Content-type: application/json';
curl_setopt($crl, CURLOPT_HTTPHEADER, $header);
curl_setopt($crl, CURLOPT_POST, true);
curl_setopt($crl, CURLOPT_POSTFIELDS, urlencode($accesstoken));
$rest = curl_exec($crl);
print_r($rest);
不工作,请帮忙.:)
更新:我接受了Jason McCreary的建议,现在我的代码如下所示:
UPDATE: I took Jason McCreary's advice and now my code looks like this:
$crl = curl_init();
$headr = array();
$headr[] = 'Content-length: 0';
$headr[] = 'Content-type: application/json';
$headr[] = 'Authorization: OAuth '.$accesstoken;
curl_setopt($crl, CURLOPT_HTTPHEADER,$headr);
curl_setopt($crl, CURLOPT_POST,true);
$rest = curl_exec($crl);
curl_close($crl);
print_r($rest);
但是我没有从中得到任何输出.我认为 cURL 在某个地方默默地失败了.请帮忙.:)
But I'm not getting any output out of this. I think cURL is silently failing somewhere. Please do help. :)
更新 2: NomikOS 的技巧为我做到了.:) :) :) 谢谢!!
UPDATE 2: NomikOS's trick did it for me. :) :) :) Thank you!!
推荐答案
@jason-mccreary 是完全正确的.此外,我建议您使用此代码以在出现故障时获取更多信息:
@jason-mccreary is totally right. Besides I recommend you this code to get more info in case of malfunction:
$rest = curl_exec($crl);
if ($rest === false)
{
// throw new Exception('Curl error: ' . curl_error($crl));
print_r('Curl error: ' . curl_error($crl));
}
curl_close($crl);
print_r($rest);
编辑 1
要调试,您可以将 CURLOPT_HEADER
设置为 true 以使用 firebug::net检查 HTTP 响应a> 或类似.
To debug you can set CURLOPT_HEADER
to true to check HTTP response with firebug::net or similar.
curl_setopt($crl, CURLOPT_HEADER, true);
编辑 2
关于 Curl 错误:SSL 证书问题,验证 CA 证书是否正常
尝试添加此标头(只是为了调试,在生产环境中您应该将这些选项保留在 true
代码>):
About Curl error: SSL certificate problem, verify that the CA cert is OK
try adding this headers (just to debug, in a production enviroment you should keep these options in true
):
curl_setopt($crl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($crl, CURLOPT_SSL_VERIFYPEER, false);
这篇关于如何在 PHP 中的 cURL POST HTTP 请求中包含 Authorization 标头?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!