2011-10-20 64 views
0

我使用下面的代码从Twitter的API获取鸣叫量:Twitter的API总是说400错误的请求

当然
$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; 

为$的用户名,而fopen的要求里面的其他变量是正确的,它产生正确的URL,因为我得到的错误:

警告:的fopen(http://api.twitter.com/1/statuses/user_timeline.json?screen_name=Schodemeiss &数= 5)function.fopen] :无法打开流:HTTP请求失败! HTTP/1.1 400 Bad Request in /home/ellexus1/public_html/settings.php on line 187

^^错误只要我尝试打开我的页面就会返回。

任何想法,为什么这可能是?我是否需要使用OAuth才能获取我的推文?我是否必须将我的网站注册为可能会发布信息的地方?

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

谢谢。

Andrew

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

+0

奇怪给出,它为我'卷曲 - D - “http://api.twitter.com/1/statuses/user_timeline.json?screen_n AME = Schodemeiss&计数= 5" ' –

回答

6

机会是你得到每小时限速

400 Bad Request: The request was invalid. An accompanying error message will explain why. This is the status code will be returned during rate limiting.

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);