我正在使用 twitter api 开发一个应用程序,其中涉及编写一个方法来检查用户是否存在。这是我的代码:
public static bool checkUserExists(string user)
{
//string URL = "https://twitter.com/" + user.Trim();
//string URL = "http://api.twitter.com/1/users/show.xml?screen_name=" + user.Trim();
//string URL = "http://google.com/#hl=en&sclient=psy-ab&q=" + user.Trim();
string URL = "http://api.twitter.com/1/users/show.json?screen_name=" + user.Trim();
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(URL);
try
{
var webResponse = (HttpWebResponse)webRequest.GetResponse();
return true;
}
//this part onwards does not matter
catch (WebException ex)
{
if (ex.Status == WebExceptionStatus.ProtocolError && ex.Response != null)
{
var resp = (HttpWebResponse)ex.Response;
if (resp.StatusCode == HttpStatusCode.NotFound)
{
return false;
}
else
{
throw new Exception("Unknown level 1 Exception", ex);
}
}
else
{
throw new Exception("Unknown level 2 Exception", ex);
}
}
}
问题是,使用任何已注释的网址(包括谷歌搜索查询)调用该方法超过 2 或 3 次都不起作用(它没有得到响应)(我认为这可能是由于 twitter API 限制)。在调试时,它表明它卡在:
var webResponse = (HttpWebResponse)webRequest.GetResponse();
我是这样称呼它的:
Console.WriteLine(TwitterFollowers.checkUserExists("handle1"));
Console.WriteLine(TwitterFollowers.checkUserExists("handle2"));
Console.WriteLine(TwitterFollowers.checkUserExists("handle3"));
Console.WriteLine(TwitterFollowers.checkUserExists("handle4"));
Console.WriteLine(TwitterFollowers.checkUserExists("handle5"));
Console.WriteLine(TwitterFollowers.checkUserExists("handle6"));
最多我得到 2-3 行输出。有人可以指出哪里出了问题吗?
更新1:
我每 15 秒发送 1 个请求(完全在限制范围内),但它仍然会导致错误。另一方面,发送请求、关闭应用程序并再次运行效果非常好(平均每 5 秒就有 1 个请求)。速率限制为每小时 150 次调用推特常见问题解答 https://dev.twitter.com/docs/rate-limiting#rest.
另外,我确实等了一段时间,并在 2 级得到了这个异常:http://pastie.org/3897499 http://pastie.org/3897499
更新2:可能听起来令人惊讶,但如果我运行 fiddler,它会完美地工作。不管我是否针对这个过程!