Twitter API总是说400个错误请求


Twitter API always saying 400 Bad Request

我使用以下代码从Twitter API检索tweet的数量:

$cache_file = "cache/$username-twitter.cache";
$last = filemtime($cache_file);
$now = time();
$interval = $interval * 60; // ten minutes
// Check the cache file age
if ( !$last || (( $now - $last ) > $interval) ) {
    // cache file doesn't exist, or is old, so refresh it
    // Get the data from Twitter JSON API
    //$json = @file_get_contents("http://api.twitter.com/1/statuses/user_timeline.json?screen_name=" . $username . "&count=" . $count, "rb");
    $twitterHandle = fopen("http://api.twitter.com/1/statuses/user_timeline.json?screen_name=$username&count=$count", "rb");
    $json  = stream_get_contents($twitterHandle);
    fclose($twitterHandle);
    if($json) {
        // Decode JSON into array
        $data = json_decode($json, true);
        $data = serialize($data);
        // Store the data in a cache
        $cacheHandle = fopen($cache_file, 'w');
        fwrite($cacheHandle, $data);
        fclose($cacheHandle);
    }
}
// read from the cache file with either new data or the old cache
$tweets = @unserialize(file_get_contents($cache_file));
return $tweets;

当然$username和fopen请求中的其他变量是正确的它会产生正确的URL因为我得到错误:

警告:fopen(http://api.twitter.com/1/statuses/user_timeline.json?screen_name=Schodemeiss&count=5) [function。fopen]: failed to open stream: HTTP请求失败!

HTTP/1.1 400错误请求/home/ellexus1/public_html/settings.php

, ^^错误返回每当我试图打开我的页面。

知道为什么会这样吗?我需要使用OAuth来获取我的tweet吗?我是否必须将我的网站注册为可能收到帖子的地方?

我真的不知道为什么会发生这种事。我的主机是JustHost.com,但我不确定这是否有什么不同。欢迎所有的想法!

谢谢。安德鲁

p。此代码位于一个函数中,其中username, interval和count被正确地传入,因此在错误代码中它创建了一个格式良好的地址。

您可能会获得速率限制

400 Bad Request:请求无效。伴随的错误消息将解释为什么。这是将返回的状态码在限速期间。

未认证呼叫每小时150个请求(基于ip寻址)

每小时350次认证呼叫请求(基于认证用户呼叫)

您必须进行身份验证以避免弹出这些错误。

并且在处理twitter时请使用cURL。我用file_get_contentsfopen来调用twitter API,发现它非常不可靠。你会时不时地被它击中。

fopen替换为

$ch = curl_init("http://api.twitter.com/1/statuses/user_timeline.json?screen_name=$username&count=$count");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$it = curl_exec($ch); //content stored in $it
curl_close($ch);

这可能有帮助

Error codes
https://developer.twitter.com/en/docs/basics/response-codes.html

错误码定义在上面的链接