How can I get a response from a server in WP7?
I'm trying to send a request with the HttpWebRequest class on WP7, but I don't get any response... Here is my code:
InitializeComponent();
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.google.com/");
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
tbResponse.Text = reader.ReadToEnd();
// Cleanup the streams and the response.
reader.Close();
dataStream.Close();
开发者_开发技巧response.Close();
Console.ReadLine();
Moreover, I use this extension: click here, but I tested it on a Windows Console Application and there wasn't any problem, so I think the problem is that I don't know something about WP7.
You need to make asynchronous requests like this:
var webRequest = (HttpWebRequest)HttpWebRequest.Create(Url);
webRequest.BeginGetResponse(new AsyncCallback(request_CallBack), webRequest );
and the response handler:
void request_CallBack(IAsyncResult result)
{
var webRequest = result.AsyncState as HttpWebRequest;
var response = (HttpWebResponse)WebRequest.EndGetResponse(result);
var baseStream = response.GetResponseStream();
// if you want to read binary response
using (var reader = new BinaryReader(baseStream))
{
DataBytes = reader.ReadBytes((int)baseStream.Length);
}
// if you want to read string response
using (var reader = new StreamReader(baseStream))
{
Result = reader.ReadToEnd();
}
}
Here is a helper class I developed to handle my web request needs during development of windows phone 7 apps:
http://www.manorey.net/mohblog/?p=17&preview=true
精彩评论