我正在使用下面的代码从Twitter检索一些数据
Dim FilterData = "follow=13,15"
Dim Request As WebRequest = HttpWebRequest.Create("https://stream.twitter.com/1/statuses/filter.json")
Request.ContentType = "application/x-www-form-urlencoded"
Request.Method = "POST"
Request.Credentials = New NetworkCredential("<Username>", "<Password>")
Request.ContentLength = FilterData.Length
Dim RequestStream = Request.GetRequestStream()
Dim RequestWriter As New StreamWriter(RequestStream)
RequestWriter.Write(FilterData)
RequestWriter.Close()
' Get the response.
Dim Response As WebResponse = Request.GetResponse()
Console.Writeline("Reached")
如果我在Request.GetResponse()
行上放置一个断点,那么它之前的所有内容都可以正常执行,但是下面的行永远不会被命中 - 也不是任何异常处理程序。我没有在输出窗口中看到任何第一次机会异常。
此调用是在工作线程上进行的,因此应用程序继续运行,但此工作人员不会执行任何其他操作。
有人可以指出错误吗?
答案 0 :(得分:3)
您正在尝试访问streaming API。流API不指定Content-Length响应头。他们不断写信回应。因此,您应该使用异步API来访问它。例如,您可以使用WebClient:
class Program
{
static void Main()
{
using (var client = new WebClient())
{
client.Credentials = new NetworkCredential("username", "password");
client.OpenReadCompleted += (sender, e) =>
{
using (var reader = new StreamReader(e.Result))
{
while (!reader.EndOfStream)
{
Console.WriteLine(reader.ReadLine());
}
}
};
client.OpenReadAsync(new Uri("https://stream.twitter.com/1/statuses/filter.json?follow=12,13"));
}
Console.ReadLine();
}
}
和VB.NET等价物:
Sub Main()
Dim client = New WebClient()
client.Credentials = New NetworkCredential("username", "password")
AddHandler client.OpenReadCompleted, Sub(sender, e)
Using reader = New StreamReader(e.Result)
While Not reader.EndOfStream
Console.WriteLine(reader.ReadLine())
End While
End Using
End Sub
client.OpenReadAsync(New Uri("https://stream.twitter.com/1/statuses/filter.json?follow=12,13"))
Console.ReadLine()
End Sub