【问题标题】:Failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request - OAuth 2.0 POST打开流失败:HTTP 请求失败! HTTP/1.0 400 错误请求 - OAuth 2.0 POST
【发布时间】:2012-04-08 22:43:40
【问题描述】:

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

警告: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')
            )
        );

        $参数 =
        数组('http' =>
            大批(
                '方法' => 'POST /o/oauth2/token HTTP/1.1',
                'header' => '主机:accounts.google.com\r\n'。
                            '内容类型:应用程序/x-www-form-urlencoded',
                '内容' => $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 //如果代码没有设置,用户一定是错误地来到这里或者拒绝访问这个程序
    {
        //header('位置:www.example.net/error.php');
    }

?>

【问题讨论】:

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


    【解决方案1】:

    file_get_contents 将向指定的 url 发出 GET 请求,但 oauth2/token 需要 POST 请求。

    参见参考Google OAuth2、PHP HTTP。

    【讨论】:

    • 啊哈,谢谢,我在网上混合和匹配示例,所以我一定是得到了一个 GET
    • 这个问题stackoverflow.com/a/2445332 怎么样?似乎仍然可以使用 file_get_contents() 发送 POST
    【解决方案2】:

    如果您使用的是 oauth2,请转到 library/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();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-12-31
      • 1970-01-01
      • 2022-10-02
      • 1970-01-01
      • 2014-12-14
      • 2012-07-26
      相关资源
      最近更新 更多