How to POST using HTTPclient content type = application/x-www-form-urlencoded

Prince Achim picture Prince Achim · Apr 1, 2017 · Viewed 111.4k times · Source

I am currently developing a wp8.1 application C#, i have managed to perform a POST method in json to my api by creating a json object (bm) from textbox.texts. here is my code below. How do i take the same textbox.text and POST them as a content type = application/x-www-form-urlencoded. whats the code for that?

            Profile bm = new Profile();
            bm.first_name = Names.Text;
            bm.surname = surname.Text;

            string json = JsonConvert.SerializeObject(bm);

            MessageDialog messageDialog = new MessageDialog(json);//Text should not be empty 
            await messageDialog.ShowAsync();

            HttpClient client = new HttpClient();
            client.DefaultRequestHeaders.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json");

            byte[] messageBytes = Encoding.UTF8.GetBytes(json);
            var content = new ByteArrayContent(messageBytes);
            content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            var response = client.PostAsync("myapiurl", content).Result;

Answer

Rawitas Krungkaew picture Rawitas Krungkaew · Apr 1, 2017
var nvc = new List<KeyValuePair<string, string>>();
nvc.Add(new KeyValuePair<string, string>("Input1", "TEST2"));
nvc.Add(new KeyValuePair<string, string>("Input2", "TEST2"));
var client = new HttpClient();
var req = new HttpRequestMessage(HttpMethod.Post, url) { Content = new FormUrlEncodedContent(nvc) };
var res = await client.SendAsync(req);

Or

var dict = new Dictionary<string, string>();
dict.Add("Input1", "TEST2");
dict.Add("Input2", "TEST2");
var client = new HttpClient();
var req = new HttpRequestMessage(HttpMethod.Post, url) { Content = new FormUrlEncodedContent(dict) };
var res = await client.SendAsync(req);