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";
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!