0

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

警告:file_get_contents(http://accounts.google.com):打开流失败:HTTP 请求失败!HTTP/1.0 405 Method Not Allowed in C:\...\index.php 第 23 行

我的代码如下:

$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

4 回答 4

0

使用了错误的 URI,(这就是为什么你没有得到允许的方法头)。访问令牌通过https://accounts.google.com/o/oauth2/token检索,需要“https”。

不相关:您的 postdata 缺少所需的“redirect_uri”。

于 2014-06-12T22:30:10.640 回答
0

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

'方法' => 'PUT'

'方法' => '发布'

于 2013-10-24T11:59:28.840 回答
0

首先,您在这里得到的是响应代码 (405),它在错误类中(400 到 499 或也写为4xx)。

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

HTTP/1.0 包括状态码在 RFC1945 中有概述:

这里的问题是没有定义代码 405(作为具体数字)。因此,文档退回到错误代码的 4xx的一般描述。

RFC2616 中概述了 HTTP/1.1:

但是,它具有405 错误代码详细信息,如代码示例中的响应标头所示:

// ...
$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 方法 POST 不受此 URL 支持

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

于 2013-10-24T12:12:20.543 回答
0

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

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

其次google要识别client_id,所以它也应该是POST参数的一部分。

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

$opts = array(
'http' => array(
    'method'  => 'POST',
    'header'  => 'Content-type: application/x-www-form-urlencoded',
    'content' => $postdata,
    'client_id' => '######################',
    'client_secret' => '##########################'
 )
)
于 2017-11-25T18:08:00.940 回答