Reading data from an open HTTP stream

前端 未结 4 602
醉梦人生
醉梦人生 2021-02-02 16:23

I am trying to use the .NET WebRequest/WebResponse classes to access the Twitter streaming API here \"http://stream.twitter.com/spritzer.json\".

I need to b

4条回答
  •  死守一世寂寞
    2021-02-02 17:10

    BeginGetResponse is the method you need. It allows you to read the response stream incrementally:

    class Program
    {
        static void Main(string[] args)
        {
            WebRequest request = WebRequest.Create("http://stream.twitter.com/spritzer.json");
            request.Credentials = new NetworkCredential("username", "password");
            request.BeginGetResponse(ar => 
            {
                var req = (WebRequest)ar.AsyncState;
                // TODO: Add exception handling: EndGetResponse could throw
                using (var response = req.EndGetResponse(ar))
                using (var reader = new StreamReader(response.GetResponseStream()))
                {
                    // This loop goes as long as twitter is streaming
                    while (!reader.EndOfStream)
                    {
                        Console.WriteLine(reader.ReadLine());
                    }
                }
            }, request);
    
            // Press Enter to stop program
            Console.ReadLine();
        }
    }
    

    Or if you feel more comfortable with WebClient (I personnally prefer it over WebRequest):

    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("http://stream.twitter.com/spritzer.json"));
    }
    Console.ReadLine();
    

提交回复
热议问题