Sample code to make a Post Request for windows phone

This bit of code makes a post request to my server with some data and reads back a response.
This works beautifully on Android and in the editor.

using (WebClient client = new WebClient())
{
    client.Encoding = System.Text.Encoding.UTF8;
    client.Headers[HttpRequestHeader.ContentType] = "application/json";

    byte[] requestData = new byte[0];
    string jsonRequest = "{}";
    if (data != null) 
    {
        string tempRequest = Converter.SerializeToString (data);
        jsonRequest = "{\"Data\": \"" + tempRequest + "\"}";

        requestData = System.Text.Encoding.UTF8.GetBytes(jsonRequest);
    }

    // below line of code is the culprit    
    byte[] returnedData = client.UploadData(url, "POST", requestData);

    if(returnedData.Length > 0)
    {
        // do stuff
    }
}

This does however NOT work on windows phone, where I get lots of complaints such as:

System.Byte> System.Net.WebClient::UploadData(System.String,System.String,System.Byte)` doesn’t exist in target framework.

It is explained here that these things dont exist on WP8 - http://docs.unity3d.com/Manual/wp8-faq.html.

So, as Im sure im not the first one wanting to do post requests on a windows phone, anyone have any suggestions as to how they should be done?

WWW or WWWForm is NOT an option as this blocks rendering thread and does not allow me to run things in the background as they are not thread safe. The above code is run on a separate thread.

Here is a separate question I made regarding unity freezing on WWW if anyone interested: Unity Freezes during yield return www; - Questions & Answers - Unity Discussions

Looks like you have to some Platform Dependent Compilation (Unity - Manual: Conditional Compilation) and add the extra parameters to windows phone.
Take a look at http://forum.unity3d.com/threads/system-text-encoding-utf8-getstring-byte-error.203175/

So you’ll end up with something like (untested!)

#if UNITY_WP8 || UNITY_WP8_1
requestData = System.Text.Encoding.UTF8.GetBytes(jsonRequest,0,jsonRequest.length);
#else
 requestData = System.Text.Encoding.UTF8.GetBytes(jsonRequest);
#endif

Hope that helped :slight_smile: