I'm trying to use the Firebase API on the Windows Phone through the EventSource / Server-Sent Events protocol.
The code below works when I don't set the Accept: text/event-stream
. In this way I get the entire requested json.
But the task doesn't continue when the Accept is set to text/event-stream.
With request.AllowReadStreamBuffering
set to false
it doesn't change
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);
}
});
Thank you!
The request.Method = "GET"
refers to the HTTP action method which is different than the PUT action of the SSE protocol. If I set the request method to PUT I get an error.
I don't know why, but I resolved upgrading to Windows Phone 8.1 and using the HTTPClient
in the Windows.Web.Http
namespace (it's not available in 8.0).
Here's the code:
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);
});
});