我在网上找到了以下代码(here)并尝试在Google App Engine上实施。
当我在localhost上运行它时,它运行得很好,但是当我将它部署到App Enginge时,我在$encodedData
中得不到任何内容。
$authContext = stream_context_create(array(
'http' => array(
'method' => 'POST',
'header' => "Authorization: Basic " . base64_encode(($consumerKey).':'.($consumerSecret)) . "\r\n".
"Content-type: application/x-www-form-urlencoded;charset=UTF-8\r\n".
"Content-Length: 29\r\n".
"\r\n".
"grant_type=client_credentials",
),
));
$authResponse = file_get_contents("https://api.twitter.com/oauth2/token", false, $authContext);
$decodedAuth = json_decode($authResponse, true);
$bearerToken = $decodedAuth["access_token"];
$context = stream_context_create(array(
'http' => array(
'method' => 'GET',
'header' => "Authorization: Bearer " . $bearerToken . "\r\n".
"\r\n".
"grant_type=client_credentials",
),
));
$encodedData = file_get_contents('https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=samkiesupdates&count='."100", false, $context);
任何知道我需要在代码中修改哪些内容以使其在Google App Engine服务器上运行的人? 也许它在我上面链接的论坛帖子的回复中说,但遗憾的是我不会说德语,所以我说不出来。
答案 0 :(得分:1)
您应该将帖子正文放在http context选项的“内容”字段中,而无需指定内容长度。
$authContext = stream_context_create(array(
'http' => array(
'method' => 'POST',
'header' => "Authorization: Basic ".base64_encode(($consumerKey).':'.($consumerSecret))."\r\n".
"Content-type: application/x-www-form-urlencoded;charset=UTF-8\r\n",
'content' => 'grant_type=client_credentials',
),
));
对你提出的其他http请求也这样做。
答案 1 :(得分:0)
只是为了清除这些内容,并使整个问题/答案更加明显。这是工作代码示例:
<?php
$consumerKey = <YOUR CONSUMER KEY>;
$consumerSecret = <YOUR CONSUMER SECRET>;
$authContext = stream_context_create(array(
'http' => array(
'method' => 'POST',
'header' => "Authorization: Basic " . base64_encode(($consumerKey).':'.($consumerSecret)) . "\r\n".
"Content-type: application/x-www-form-urlencoded;charset=UTF-8\r\n",
'content' => "grant_type=client_credentials"
),
));
$authResponse = file_get_contents("https://api.twitter.com/oauth2/token", false, $authContext);
$decodedAuth = json_decode($authResponse, true);
$bearerToken = $decodedAuth["access_token"];
$context = stream_context_create(array(
'http' => array(
'method' => 'GET',
'header' => "Authorization: Bearer " . $bearerToken . "\r\n",
'content' => "grant_type=client_credentials"
),
));
$encodedData = file_get_contents('https://api.twitter.com/1.1/statuses/show.json?id=<YOUR TWEET ID>', false, $context);
$result = json_decode($encodedData);
感谢您的帮助,
尼克