Many times in application development using C# it is required to to post some data to a specific URL. In this article I will show two options for implementing this :
1) Using WebClient
string url = "http://www.url.com/post.aspx";
string params = "param1=value1¶m2=value2";
using (WebClient wc = new WebClient())
{
wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
string HtmlResult = wc.UploadString(url, params);
}
2) Using HttpClient
using (var client = new HttpClient())
{
var data = new Dictionary<string, string>
{
{ "key1", "value1" },
{ "key2", "value2" }
};
var content = new FormUrlEncodedContent(data);
var response = await client.PostAsync("http://www.url.com/post.aspx", content);
var responseString = await response.Content.ReadAsStringAsync();
}
Out of the two approaches shown above using the HttpClient is the preferred approach.
0 Comment(s)