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


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

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);

 

How to post data using HttpClient?

You need to use:

await client.PostAsync(uri, content); 

Something like that:

var comment = "hello world"; var questionId = 1; var formContent = new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>("comment", comment), new KeyValuePair<string, string>("questionId", questionId) }); var myHttpClient = new HttpClient(); var response = await myHttpClient.PostAsync(uri.ToString(), formContent); 

And if you need to get the response after post, you should use:

var stringContent = await response.Content.ReadAsStringAsync(); 

Hope it helps ;)

 

 

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM