Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • C# : How to post data to specific URL using C# ?

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 5.26k
    Comment on it

    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&param2=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)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: