i've been reading here for quite a long time, but in this case i'm not getting any further. I'm rather new to Windows Phone development and facing the following problem.
I'm calling a webservice were I have to post a xml request message. I've got the code working in regular c# (see code below)
private static string WebRequestPostData(string url, string postData) { System.Net.WebRequest req = System.Net.WebRequest.Create(url); req.ContentType = "text/xml"; req.Method = "POST"; byte[] bytes = System.Text.Encoding.ASCII.GetBytes(postData); req.ContentLength = bytes.Length; using (Stream os = req.GetRequestStream()) { os.Write(bytes, 0, bytes.Length); } using (System.Net.WebResponse resp = req.GetResponse()) { if (resp == null) return null; using (System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream())) { return sr.ReadToEnd().Trim(); } } } But for Windows Phone (8) development it needs to be async. After searching the web, and trying the various samples given here I came to the following code:
private async void DoCallWS() { string url = "<my_url>"; // HTTP web request var httpWebRequest = (HttpWebRequest)WebRequest.Create(url); httpWebRequest.ContentType = "text/xml"; httpWebRequest.Method = "POST"; // Write the request Asynchronously using (var stream = await Task.Factory.FromAsync<Stream>(httpWebRequest.BeginGetRequestStream, httpWebRequest.EndGetRequestStream, null)) { string requestXml = "<my_request_xml>"; // convert request to byte array byte[] requestAsBytes = Encoding.UTF8.GetBytes(requestXml); // Write the bytes to the stream await stream.WriteAsync(requestAsBytes , 0, requestAsBytes .Length); stream.Position = 0; using (StreamReader reader = new StreamReader(stream, Encoding.UTF8)) { //return reader.ReadToEnd(); string result = reader.ReadToEnd(); } } } The string result has the value of my request xml message i'm trying to sent....
I'm aware that async void methodes are not preferred but i will fix that later.
I've also tried to following the solution as described by Matthias Shapiro (http://matthiasshapiro.com/2012/12/10/window-8-win-phone-code-sharing-httpwebrequest-getresponseasync/) but that caused the code to crash
Please point me in the right direction :)
Thnx Frank