Firebase:在Windows Phone上使用Accept:text / event-stream

时间:2014-09-17 15:56:32

标签: c# windows-phone-8 firebase event-stream

我正在尝试通过EventSource / Server-Sent Events协议在Windows Phone上使用Firebase API。

当我未设置Accept: text/event-stream时,以下代码有效。通过这种方式,我得到了整个请求的json。 但是当 Accept 设置为 text / event-stream 时,任务不会继续。

request.AllowReadStreamBuffering设置为false时,它不会更改

var request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "GET";
request.AllowAutoRedirect = true;
request.Accept = "text/event-stream";
//request.AllowReadStreamBuffering = false;

Task.Factory.FromAsync<WebResponse>(request.BeginGetResponse,
                                                        request.EndGetResponse,
                                                        null)
            .ContinueWith(async t => 
                { 
                    using (Stream s = t.Result.GetResponseStream())
                    {
                        byte[] buffer = new byte[1024 * 8];
                        int bytesRead = await s.ReadAsync(buffer, 0, buffer.Length);

                        string content = Encoding.UTF8.GetString(buffer, 0, bytesRead);
                        System.Diagnostics.Debug.WriteLine(content);
                    }
                });

谢谢!

1 个答案:

答案 0 :(得分:1)

request.Method = "GET"指的是HTTP动作方法,它与SSE协议的PUT动作不同。如果我将请求方法设置为PUT,我会收到错误。

我不知道为什么,但我解决了升级到Windows Phone 8.1并使用HTTPClient命名空间中的Windows.Web.Http(它在8.0中不可用)。

以下是代码:

    Uri url = new Uri("https://test.firebaseio.com/...");
    var request = new HttpClient();
    request.DefaultRequestHeaders.Accept.Clear();
    request.DefaultRequestHeaders.Accept.Add(new Windows.Web.Http.Headers.HttpMediaTypeWithQualityHeaderValue("text/event-stream"));

    Task task = request.GetAsync(url, HttpCompletionOption.ResponseHeadersRead).AsTask().ContinueWith(t =>
         {
             t.Result.Content.ReadAsInputStreamAsync().AsTask().ContinueWith(async t1 =>
                {
                    IInputStream istr = await t1;
                    Stream s = istr.AsStreamForRead();

                    byte[] buffer = new byte[1024 * 8];
                    int bytesRead = await s.ReadAsync(buffer, 0, buffer.Length);

                    string content = Encoding.UTF8.GetString(buffer, 0, bytesRead);
                    System.Diagnostics.Debug.WriteLine(content);
                });
        });