我正在创建一个与HTTP侦听器服务通信的应用程序。
我已从此Posting Posting with HttpWebRequest on Windows Phone 7
中获取代码这段代码似乎工作得非常完美,只是在第一次调用时才起作用。
调用正在进行服务,并没有抛出错误。只是返回值为空。
在第二次通话中,我没有问题地获得返回值。如果我再转到另一页并再次返回,我也会第一次获得返回值。这仅在首次启动应用时第一次调用时发生。
任何想法都将不胜感激。代码如下。
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(手机应用)
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;
答案 0 :(得分:0)
答案是手机继续,所以当页面更新时,仍然没有数据存在。