2

我正在尝试通过 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);
                    }
                });

谢谢!

4

1 回答 1

1

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

我不知道为什么,但我解决了升级到 Windows Phone 8.1 并HTTPClientWindows.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);
                });
        });
于 2014-09-22T13:00:40.937 回答