如何在PHP中的cURL POST HTTP请求中包含Authorization标头?

问题描述 投票:47回答:3

我正试图通过Gmails OAuth 2.0访问用户的邮件,我正在通过Google的OAuth 2.0 Playground来解决这个问题

在这里,他们已经指定我需要将其作为HTTP REQUEST发送:

POST /mail/feed/atom/ HTTP/1.1
Host: mail.google.com
Content-length: 0
Content-type: application/json
Authorization: OAuth SomeHugeOAuthaccess_tokenThatIReceivedAsAString

我已经尝试编写代码来发送此REQUEST,如下所示:

$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的建议,现在我的代码看起来像这样:

$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在某个地方默默地失败了。请帮忙。 :)

更新2:NomikOS的伎俩为我做了。 :) :) :) 谢谢!!

php http curl oauth
3个回答
19
投票

@ jason-mccreary完全正确。此外,我建议你这个代码,以便在出现故障时获得更多信息:

$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响应。

curl_setopt($crl, CURLOPT_HEADER, true);

编辑2

关于Curl error: SSL certificate problem, verify that the CA cert is OK尝试添加此标题(仅用于调试,在生产环境中,您应该在true中保留这些选项):

curl_setopt($crl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($crl, CURLOPT_SSL_VERIFYPEER, false);

37
投票

你有大部分代码......

CURLOPT_HTTPHEADERcurl_setopt()采用一个数组,每个标题作为一个元素。你有一个元素有多个标题。

您还需要将Authorization标头添加到$header阵列。

$header = array();
$header[] = 'Content-length: 0';
$header[] = 'Content-type: application/json';
$header[] = 'Authorization: OAuth SomeHugeOAuthaccess_tokenThatIReceivedAsAString';

0
投票

使用“Content-type:application / x-www-form-urlencoded”而不是“application / json”

© www.soinside.com 2019 - 2024. All rights reserved.