无法打开流:HTTP请求失败! HTTP / 1.0 400错误请求 - OAuth 2.0 POST

时间:2012-03-24 19:54:18

标签: post https google-api file-get-contents http-status-code-400

我正在为我的大学项目使用YouTube API,并且我一直收到错误消息。在这里,我将它们发送到授权页面进行登录,当它们允许访问时,它会发回$ _GET ['code']字符串。然后我发送它和其他一些数据,它应该发回一个JSON对象。相反,我只是得到了

  

警告:file_get_contents(https://accounts.google.com/o/oauth2/token)   [function.file-get-contents]:无法打开流:HTTP请求   失败!第27行http://www.example.net/callback.php中的HTTP / 1.0 400错误请求

为了安全起见,我已经用example.net替换了我的域名

 urlencode($_GET['code']),
                'client_id' => urlencode('111522767640.apps.googleusercontent.com '),
                'client_secret' => urlencode('secret'),
                'redirect_uri' => urlencode('http://example.net/callback.php'),
                'grant_type' => urlencode('authorization_code')
            )
        );

        $params = 
        array('http' =>
            array(
                'method'  => 'POST /o/oauth2/token HTTP/1.1',
                'header'  => 'Host: accounts.google.com\r\n'.                           
                            'Content-Type: application/x-www-form-urlencoded',
                'content' => $postdata
            )
        );

        $context = stream_context_create($params);
        $result = file_get_contents('https://accounts.google.com/o/oauth2/token', false,$context);
        var_dump($_SESSION);
        var_dump($result);
    }
    else //If code isnt set, user must have come here erroniously or has denied access to this program
    {
        //header( 'Location: www.example.net/error.php' ) ;
    }

?>

2 个答案:

答案 0 :(得分:0)

file_get_contents将对指定的网址发出GET个请求,但oauth2/token需要POST个请求。

参见参考Google OAuth2PHP HTTP

答案 1 :(得分:0)

如果您使用oauth2,请转到libraries / oauth2 / provider.php并取消注释代码行182显示

            $ci = get_instance();
            $ci->load->spark('curl/1.2.1');
            $ci->curl
                ->create($url)
                ->post($params, array('failonerror' => false));

            $response = $ci->curl->execute();