【发布时间】:2020-04-05 18:19:54
【问题描述】:
我想将这个用于 Google 提醒的开源 Python 库移植到 PHP:
https://github.com/jonahar/google-reminders-cli
我已经在 https://developers.google.com/identity/protocols/OAuth2WebServer
我的 PHP 版本:https://github.com/Jinjinov/google-reminders-php
现在我需要移植 Python 的 oauth2client POST 请求:
body = {
'5': 1, # boolean field: 0 or 1. 0 doesn't work ¯\_(ツ)_/¯
'6': num_reminders, # number number of reminders to retrieve
}
HEADERS = {
'content-type': 'application/json+protobuf',
}
response, content = self.auth_http.request(
uri='https://reminders-pa.clients6.google.com/v1internalOP/reminders/list',
method='POST',
body=json.dumps(body),
headers=HEADERS,
)
使用https://github.com/googleapis/google-api-php-client进行授权
我的 Guzzle 客户端 POST 请求返回 HTTP 400 - 错误请求 - 即使 Python 版本运行正常。
我用过:
- http://docs.guzzlephp.org/en/stable/request-options.html#headers
- http://docs.guzzlephp.org/en/stable/request-options.html#body
我的代码(带有授权和 $httpClient 的完整代码在 GitHub 上):
function list_reminders($httpClient, $num_reminders) {
$body = (object)[
'5' => 1, // boolean field: 0 or 1. 0 doesn't work ¯\_(ツ)_/¯
'6' => $num_reminders, // number of reminders to retrieve
];
$response = $httpClient->request(
'POST',
'https://reminders-pa.clients6.google.com/v1internalOP/reminders/list',
[
'headers' => [ 'content-type' => 'application/json' ],
'body' => json_encode($body)
]
);
if ($response->getStatusCode() == $HTTP_OK) {
$content = $response->getBody();
$content_dict = json_decode($content);
if (!array_key_exists('1', $content_dict)) {
return [];
}
$reminders_dict_list = $content_dict['1'];
$reminders = [];
foreach($reminders_dict_list as $reminder_dict) {
array_push($reminders, build_reminder($reminder_dict));
}
return $reminders;
}
else {
return null;
}
}
【问题讨论】:
-
您的 Content-Type 标头似乎有所不同,我也怀疑
$body = (object)[…]您会以正确的格式发送数据。您可能应该以 API 实际期望的任何格式提供字符串形式的正文内容。 -
@04FS 抱歉,因为我是复制粘贴代码,所以我删除了太多 - 我编辑了问题
-
@04FS 因为还有其他几个错误,更改 Content-Type 标头似乎没有任何区别,但最终是一个关键的修复,所以 50 点赏金是你的,如果你想要 - 谢谢!
标签: php python post guzzle google-oauth