Twitter API调用间歇性失败

问题描述:

我使用PHP来显示用户最近的推文。这是在Wordpress中。这工作的大部分时间 - 但有时,我得到这个错误:Twitter API调用间歇性失败

file_get_contents(http://api.twitter.com/1/statuses/user_timeline/[username].json) [function.file-get-contents]: failed to open stream: HTTP request failed! HTTP/1.1 400 Bad Request in [...]/twitter.php on line 47

我绝对可以肯定,我不会在Twitter的API限制,因为即使我的缓存代码是有缺陷的,没有一个人其他人可以看到这一点 - 它在本地托管 - 并且我无法在一个小时内查看该页面150次。我测试过用户名和数据库条目确实正在被检索。这是我的代码:

<?php 
function twitter($username) { 
$tweet = ''; 
echo $username; 
if (!get_option('twitter_last_updated')) { 
    $format='json'; 
    $tweet_raw=file_get_contents("http://api.twitter.com/1/statuses/user_timeline/{$username}.{$format}"); 
    $tweet = json_decode($tweet_raw); 
    add_option('twitter_last_updated', time(), "", "yes"); 
    add_option('twitter_last_updated_author', $username, "", "yes"); 
    add_option('twitter_last_updated_data', $tweet_raw, "", "yes"); 
} elseif (time() - get_option('twitter_last_updated') > 30 || get_option('twitter_last_updated_author') != $username) { 
    $format='json'; 
$tweet_raw=file_get_contents("http://api.twitter.com/1/statuses/user_timeline/{$username}.{$format}"); 
    $tweet = json_decode($tweet_raw); 
    update_option('twitter_last_updated', time()); 
    update_option('twitter_last_updated_author', $username); 
    update_option('twitter_last_updated_data', $tweet_raw); 
} else { 
$tweet = json_decode(get_option('twitter_last_updated_data')); 
} ?> 
<!-- display the tweet --> 
<?php } ?> 

我真的很感谢这个帮助。我感到完全难住。

+5

根据我的经验,有关Twitter的所有内容都会间歇性地失败。 – JAL 2010-07-10 21:31:33

首先,你不应该使用的file_get_contents来通过网络检索“文件”来。你应该使用卷曲。这可能只是系统响应延迟,或者Twitter发布重定向以实现负载平衡。 file_get_contents不遵循重定向,并立即超时。如果没有指定超时,Curl可以设置为遵循重定向并遵守网络超时(我认为1分钟)。最重要的是,卷曲可以说明它为什么失败。

+0

Curl是否默认安装了PHP?你看,我正在制作一个高级的WordPress主题,所以我需要确保我使用的任何东西都将安装在客户使用的任何服务器上。 – Debashis 2010-07-10 22:20:25

+0

我还没有找到没有cURL的地方,并且在某些主机(特别是共享主机)上禁用远程'file_get_contents'。 – ceejayoz 2010-07-10 22:48:19

+0

非常感谢,我用cURL工作。 – Debashis 2010-07-10 23:07:22

你多久打一次电话?如果我没有记错的话,twitter最近每小时将每小时的通话数量从150个变为每小时75个。您可能需要缓存结果,以免用尽补贴。

看到这个Slashdot的故事:Twitter Throttling hits 3rd party apps

+0

是的,我也一直在这一点。我的版本使用客户端JavaScript,但在调试其他问题时,我注意到我的Twitter消息已关闭,我花了一段时间才弄清楚为什么...... – 2010-07-10 21:43:22

+0

我怀疑我每小时调用超过20次,因为我说,这只是我。 – Debashis 2010-07-10 22:20:53

为什么不使用WordPress HTTP API?这正是它的设计目的 - 一个使用标准WordPress功能处理HTTP的封装器,无论平台或设置如何。

我写了一个类似于你所拥有的东西,它每3个请求都会失败,解决方案是在file_get_contents上建立一个小缓存系统和@以避免PHP将错误返回给用户。

当twitter失败时,它会失败很多,你只是从先前构建的缓存中获取数据。

我也不建议你添加这个onfly,它可能会减慢整个页面的建设,因为twitter的问题。