Google服务器不支持POST请求

时间:2013-10-24 11:52:54

标签: php oauth-2.0 httpcontext google-authentication

从我的服务器向google.com发送请求时出现以下错误:

  

警告:file_get_contents(http://accounts.google.com):无法打开流:HTTP请求失败!第23行的C:\ ... \ index.php中不允许使用HTTP / 1.0 405方法

我的代码如下:

$postdata = http_build_query(
    array(
        'code'          => '####',
        'client_id'     => '####',
        'client_secret' => '####',
        'grant_type'    => 'authorization_code'
    )
);

$opts = array(
    'http' => array(
        'method'  => 'POST',
        'header'  => 'Content-type: application/x-www-form-urlencoded',
        'content' => $postdata
    )
);

$context = stream_context_create($opts);

$result = file_get_contents('http://accounts.google.com', false, $context);

echo $result;

4 个答案:

答案 0 :(得分:0)

您选择的方法是“PUT”而不是“POST”。如果您想以POST发送请求,请更改

  

'method'=> 'PUT'

  

'method'=> 'POST'

答案 1 :(得分:0)

首先,你得到的是一个响应代码(405),它在错误类中(400到499或者也写成 4xx )。

因此,服务器会在协议级别向您报告错误。使用的协议也被命名为:HTTP,更具体地说是HTTP / 1.0。

RFC1945中概述了包含状态代码的HTTP / 1.0:

这里的问题是没有定义代码405(作为具体数字)。因此,文档可以回溯到4xx for error codes的一般描述。

RFC2616中概述了HTTP / 1.1:

但它有the 405 error code details,因为代码示例中的响应标题显示:

// ...
$result = file_get_contents('http://accounts.google.com', false, $context);

var_dump($http_response_header);

输出:

array(6) {
  [0] => string(31) "HTTP/1.0 405 Method Not Allowed"
  [1] => string(38) "Content-Type: text/html; charset=UTF-8"
  [2] => string(19) "Content-Length: 958"
  [3] => string(35) "Date: Thu, 24 Oct 2013 12:03:09 GMT"
  [4] => string(15) "Server: GFE/2.0"
  [5] => string(27) "Alternate-Protocol: 80:quic"
}

所需的响应列表显示另一个协议违规,因为所需的Allow标头不是响应的一部分。它会显示允许哪些方法。

所以你所能做的就是尝试使用普通的HTTP方法而不是PUT,你可能正在寻找POST。让我们用POST运行示例,但没有运气:

  

警告:file_get_contents(http://accounts.google.com):无法打开流:HTTP请求失败! HTTP / 1.0 405 HTTP方法此URL不支持POST

我建议您与Google(您向其发送HTTP请求的在线服务的供应商)联系,并询问您需要匹配的技术规范,以满足您的要求。出于调试目的,我建议您阅读PHP的特殊$http_response_header变量,我有一些示例代码和解释以及有关PHP's HTTP Wrapper的错误处理的一些提示:

答案 2 :(得分:0)

使用错误的URI,(这就是为什么你没有得到允许的方法标题)。访问令牌通过https://accounts.google.com/o/oauth2/token" https"是必须的。

无关:您的postdata缺少必需的" redirect_uri"。

答案 3 :(得分:0)

现在已经很晚了,希望它可以帮助像我这样的其他人。

有两个问题。首先,无法使用client_secret生成访问令牌。因此,必须包含成功请求client_secret

其次谷歌想要识别client_id,因此它也应该是POST参数的一部分。

生成访问令牌的正确参数应该是

$opts = array(
'http' => array(
    'method'  => 'POST',
    'header'  => 'Content-type: application/x-www-form-urlencoded',
    'content' => $postdata,
    'client_id' => '######################',
    'client_secret' => '##########################'
 )
)