Http Post for Windows Phone 8

I am also currently working on a Windows Phone 8 project and here is how I am posting to a server. Windows Phone 8 sort of has limited access to the full .NET capabilities and most guide I read say you need to be using the async versions of all the functions.

// server to POST to
string url = "myserver.com/path/to/my/post";

// HTTP web request
var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.ContentType = "text/plain; charset=utf-8";
httpWebRequest.Method = "POST";

// Write the request Asynchronously 
using (var stream = await Task.Factory.FromAsync<Stream>(httpWebRequest.BeginGetRequestStream,          
                                                         httpWebRequest.EndGetRequestStream, null))
{
   //create some json string
   string json = "{ \"my\" : \"json\" }";

   // convert json to byte array
   byte[] jsonAsBytes = Encoding.UTF8.GetBytes(json);

   // Write the bytes to the stream
   await stream.WriteAsync(jsonAsBytes, 0, jsonAsBytes.Length);
}

Leave a Comment