MrMister MrMister - 27 days ago 18
C# Question

Pass POST variables with Windows Phone App

I'm trying to insert Data from a Windows Phone App into a Database using a php script.
This is my C# code I execute when clicking on a button.

var request = WebRequest.Create(new Uri("xxx/Insert.php")) as HttpWebRequest;
request.Method = "POST";
string postdata = "Title=test&CategoryID=1";
byte[] data = Encoding.UTF8.GetBytes(postdata);
using (var requestStream = await Task<Stream>.Factory.FromAsync(request.BeginGetRequestStream, request.EndGetRequestStream, request))
{
await requestStream.WriteAsync(data, 0, data.Length);
}


I get the variable in the php script with

<?php
$title = $_POST["Title"];
$categoryID = $_POST["CategoryID"];
...
?>


Someone had the same problem here, but the solution didn't work, because
1.) WebClient is not available for WP8
2.) The second solution throws an Exception in App.i.g.cs at the line global::System.Diagnostics.Debugger.Break()

The problem is simply nothing happens. Has anybody encountered with the same problem?

Answer

I solved the Problem using System.Net.Http.HttpClient and System.Net.Http.FormUrlEncodedContent.

using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri("baseUrl.net");
                var content = new FormUrlEncodedContent(new[]
            {
                new KeyValuePair<string, string>("Title", "test")
            });

                var result = await client.PostAsync("/insert.php", content);
                string resultContent = "result: "+result.Content.ReadAsStringAsync().Result;

EDIT: awaiting the PostAsync of the client