使用stream_context_create进行POST请求--结果返回false:

9
也许有人可以指出我在这里做错了什么。我正在使用Google API和OAuth来注册用户到我的应用程序。我发现他们提供的PHP代码相当繁琐,所以我决定更多地练习执行https请求等操作。到目前为止,我已经取得了一些成功,但获取交换用户信息的令牌的最后一步需要使用POST方法。仅仅重定向浏览器,通过GET方法复制最终的URL会返回一个错误。我即将开始挖掘cURL扩展,但也许有人能够发现这段代码有什么问题?
$url = "https://accounts.google.com/o/oauth2/token";
$fields = array(
    'code' => $_GET['code'],
    'client_id' => $google['clientID'],
    'client_secret' => $google['clientSecret'],
    'redirect_uri' => "http://www.qwiku.com/scripts/php/google/reg_response.php",
    'grant_type' => "authorization_code"
);

$data = http_build_query($fields);

echo $data."<br />";

$context = stream_context_create(array(
    'http' => array(
        'method' => 'POST',
        'header' => 'Content-Type: application/x-www-form-urlencoded',
        'content' => $data
    )
));

$result = file_get_contents($url, false, $context);

var_dump($result);  

结果的转储是错误的。你可以在这里看到Google文档,但我99%确定数据被正确地格式化了。http://code.google.com/apis/accounts/docs/OAuth2WebServer.html#formingtheurl 更新:我现在正在使用curl,它似乎正在工作。唯一的问题是Google返回一个“invalid_grant”的错误。不知道为什么,因为它被设置为他们指定的确切内容。
$url = 'https://accounts.google.com/o/oauth2/token';
$ch = curl_init($url);

curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

$response = curl_exec($ch);
curl_close($ch);

更新2

我刷新了整个过程,因为我只是在刷新重定向,结果它成功了。代码可能已经过期了。


将POST更改为GET,它就会运行。 - umairhhhs
也许这可以帮到你?https://dev59.com/SWkw5IYBdhLWcg3wQoSm - func0der
你再次尝试使用流了吗? - t1gor
2个回答

1
你的方法看起来很好,

<?php
$data = http_build_query(....

$response = @file_get_contents('https://accounts.google.com/o/oauth2/token', false, stream_context_create([
'http' => [ 'method'          => 'POST'
          , 'follow_location' => true
          , 'content'         => $data
          , 'header'          => implode("\r\n", ['Accept: */*'
                                                , 'Connection: keep-alive'
                                                , 'Content-Type: application/x-www-form-urlencoded; charset=UTF-8'
                                                , 'User-Agent: jacob']) . "\r\n"
]]));
?>

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接