Canonical HTTP POST code?

2019-03-15 02:47发布

问题:

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.

回答1:

I believe that the simple version of this would be

var client = new WebClient();
return client.UploadString(url, data);

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 and System.Net.HttpWebResponse instead.



回答2:

As others have said, WebClient.UploadString (or UploadData) is the way to go.

However the built-in WebClient has a major drawback : you have almost no control over the WebRequest that is used behind the scene (cookies, authentication, custom headers...). A simple way to solve that issue is to create your custom WebClient and override the GetWebRequest 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-aware WebClient. It's so simple it makes me wonder why the built-in WebClient doesn't handle it out-of-the-box...



回答3:

Compare:

// create a client object
using(System.Net.WebClient client = new System.Net.WebClient()) {
    // performs an HTTP POST
    client.UploadString(url, xml);  

}

to

string HttpPost (string uri, string parameters)
{ 
   // parameters: name1=value1&name2=value2 
   WebRequest webRequest = WebRequest.Create (uri);
   webRequest.ContentType = "application/x-www-form-urlencoded";
   webRequest.Method = "POST";
   byte[] bytes = Encoding.ASCII.GetBytes (parameters);
   Stream os = null;
   try
   { // send the Post
      webRequest.ContentLength = bytes.Length;   //Count bytes to send
      os = webRequest.GetRequestStream();
      os.Write (bytes, 0, bytes.Length);         //Send it
   }
   catch (WebException ex)
   {
      MessageBox.Show ( ex.Message, "HttpPost: Request error", 
         MessageBoxButtons.OK, MessageBoxIcon.Error );
   }
   finally
   {
      if (os != null)
      {
         os.Close();
      }
   }

   try
   { // get the response
      WebResponse webResponse = webRequest.GetResponse();
      if (webResponse == null) 
         { return null; }
      StreamReader sr = new StreamReader (webResponse.GetResponseStream());
      return sr.ReadToEnd ().Trim ();
   }
   catch (WebException ex)
   {
      MessageBox.Show ( ex.Message, "HttpPost: Response error", 
         MessageBoxButtons.OK, MessageBoxIcon.Error );
   }
   return null;
} // end HttpPost 

Why are people using/writing the latter?