我正在使用 twitter 流 API (C#) 并定期(每 12 小时或类似的时间)获取 IOE 异常,而 Stream reader 正在尝试读取 JSON 对象(readLine)。请查看异常和下面的代码。任何帮助将不胜感激。先感谢您。
无法从传输连接中读取数据:连接尝试失败,因为连接方在一段时间后没有正确响应,或者建立连接失败,因为连接的主机没有响应。
string userName = "XXXX";
string password = "XXXX";
string url = @"https://stream.twitter.com/1.1/statuses/filter.json";
string parameters = "follow=" + userIds +"&track=" + keywords;
// Request and Response
HttpWebRequest webRequest = null;
HttpWebResponse webResponse = null;
StreamReader streamReader = null;
byte[] byteArray;
// Establishing connection with twitter filter.json
byteArray = Encoding.UTF8.GetBytes(parameters);
webRequest = (HttpWebRequest) WebRequest.Create(url);
webRequest.Credentials = new NetworkCredential(userName, password);
webRequest.Timeout = 100000;
Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
byte[] postData = encode.GetBytes(parameters);
webRequest.ContentLength = postData.Length;
Stream twitterPost = webRequest.GetRequestStream();
twitterPost.Write(postData, 0, postData.Length);
twitterPost.Close();
webResponse = (HttpWebResponse)webRequest.GetResponse();
streamReader = new StreamReader(webResponse.GetResponseStream(), encode);
Stopwatch sw = new Stopwatch();
sw.Start();
while (sw.Elapsed < TimeSpan.FromDays(365))
{
String json = streamReader.ReadLine(); // [The program stop here. throws exception]
if (json == "")
{
continue;
}
Packet dataPacket = new Packet() { json = json, id = id++ };
ThreadPool.QueueUserWorkItem(new WaitCallback(Execute), dataPacket);
}
// Aborting the request and closing the stream
webRequest.Abort();
sw.Stop();
streamReader.Close();
streamReader = null;
webResponse.Close();
webResponse = null;