I am creating an app that will talk to a HTTP Listener service.
I have taken code from this Posting Posting with HttpWebRequest on Windows Phone 7
This code seems to work almost perfectly, it just doesn't work on the very first call.
The call is making it to the service and is not throwing an error. Just the return value is empty.
On the second call, I am getting the return value without problem. If I go to another page and back again, I also get the return value first time. This is only happening on the first call when the app is first started.
Any ideas would be greatly appreciated. Code Below.
SERVICE
DiagnosticLog.Write(99, DateTime.Now, "Phone Listener Called");
IAsyncResult phoneResult = PhoneListener.BeginGetContext(new AsyncCallback(Phone), PhoneListener);
HttpListenerContext context = null;
HttpListenerResponse response = null;
HttpListener _listener = (HttpListener)result.AsyncState;
context = _listener.EndGetContext(result);
HttpListenerRequest request = context.Request;
response = context.Response;
//response.ContentType = "text/plain";
string postData = string.Empty;
using (StreamReader sr = new StreamReader(request.InputStream))
{
DiagnosticLog.Write(99, DateTime.Now, "Reading Stream");
postData = sr.ReadToEnd();
}
byte[] buffer;
System.IO.Stream output = response.OutputStream;
if (postData == "islogin")
{
buffer = System.Text.Encoding.UTF8.GetBytes("logincorrect");
// Get a response stream and write the response to it.
response.ContentLength64 = buffer.Length;
output = response.OutputStream;
output.Write(buffer, 0, buffer.Length);
DiagnosticLog.Write(99, DateTime.Now, "Good Return sent");
output.Close();
}
else
{
buffer = System.Text.Encoding.UTF8.GetBytes("loginincorrect");
// Get a response stream and write the response to it.
response.ContentLength64 = buffer.Length;
output = response.OutputStream;
output.Write(buffer, 0, buffer.Length);
DiagnosticLog.Write(99, DateTime.Now, "Bad Return sent");
output.Close();
}
CODE (phone app)
WebRequest request = WebRequest.Create("http://127.0.0.1:8080/phone");
request.Method = "POST";
request.BeginGetRequestStream(ar =>
{
var requestStream = request.EndGetRequestStream(ar);
using (StreamWriter sw = new StreamWriter(requestStream))
{
sw.Write("islogin");
}
request.BeginGetResponse(a =>
{
try
{
WebResponse response = request.EndGetResponse(a);
Stream responseStream = response.GetResponseStream();
using(var sr = new StreamReader(responseStream))
{
Storage.ReturnValue = sr.ReadToEnd().ToString();
}
}
catch(WebException ex)
{
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
MessageBox.Show(ex.ToString());
});
}
}, null);
}, null);
txtLoginUsername.Text = Storage.ReturnValue;