I've seen so many implementations of sending an http post, and admittedly I don't fully understand the underlying details to know what's required.
What is the succinct/correct/canonical code to send an HTTP POST in C# .NET 3.5?
I want a generic method like
public string SendPost(string url, string data)
that can be added to a library and always used for posting data and will return the server response.
I believe that the simple version of this would be
The
System.Net.WebClient
class has other useful methods that let you download or upload strings or a file, or bytes.Unfortunately there are (quite often) situations where you have to do more work. The above for example doesn't take care of situations where you need to authenticate against a proxy server (although it will use the default proxy configuration for IE).
Also the WebClient doesn't support uploading of multiple files or setting (some specific) headers and sometimes you will have to go deeper and use the
System.Web.HttpWebRequest
andSystem.Net.HttpWebResponse
instead.As others have said,
WebClient.UploadString
(orUploadData
) is the way to go.However the built-in
WebClient
has a major drawback : you have almost no control over theWebRequest
that is used behind the scene (cookies, authentication, custom headers...). A simple way to solve that issue is to create your customWebClient
and override theGetWebRequest
method. You can then customize the request before it is sent (you can do the same for the response by overridingGetWebResponse
). Here is an example of a cookie-awareWebClient
. It's so simple it makes me wonder why the built-in WebClient doesn't handle it out-of-the-box...Compare:
to
Why are people using/writing the latter?