20 November, 2010

WP7: How to make (async) HttpRequests from Windows Phone 7 application

Had a little challenge today about calling out to a JSON endpoint from a phone application. It turned out to be quite easy – but it took some time to have it setup correctly! Hope this helps others facing the same problems.


First – calls to anything “outside” the phone should be done asynchronously to make the UI responsive while the call is taking place:

var req = (HttpWebRequest)WebRequest.Create(@http://www.abzcompany.net/infoservice.svc/json/GetAllData);
req.Method = "POST";
req.ContentType = "application/json; charset=utf-8";

//call async
req.BeginGetResponse(new AsyncCallback(jsonGetRequestStreamCallback), req);

Next – await the call back in a new method:
void jsonGetRequestStreamCallback(IAsyncResult asynchronousResult)
WebResponse response = ((HttpWebRequest)asynchronousResult.AsyncState).EndGetResponse(asynchronousResult);
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
string responseString = reader.ReadToEnd();

//deserialize using datacontract serializer (not shown)


That’s how easy it is!

Technorati Tags:


Merengil said...

Thanks a lot, it works pretty well!
Finally, these 2 days paid off :)

ram said...

this is nice for hit the url..but i have json file(data.json).how can i
extract data from it..
plz help me

Claus Konrad said...

Simple fileread...?

ram said...

sir i try it as much as i can..but no
response ..plz give me a sample code..am also fresher to c#..if u provide it means which is use full