[.NET][C#] This C# code snippet performs an HTTP Post and returns the response as a string.


SUBMITTED BY: Guest

DATE: Dec. 7, 2013, 4:14 p.m.

FORMAT: Text only

SIZE: 1.7 kB

HITS: 54657

  1. This C# code snippet performs an HTTP Post and returns the response as a string.
  2. using System.Net;
  3. ...
  4. string HttpPost (string uri, string parameters)
  5. {
  6. // parameters: name1=value1&name2=value2
  7. WebRequest webRequest = WebRequest.Create (uri);
  8. //string ProxyString =
  9. // System.Configuration.ConfigurationManager.AppSettings
  10. // [GetConfigKey("proxy")];
  11. //webRequest.Proxy = new WebProxy (ProxyString, true);
  12. //Commenting out above required change to App.Config
  13. webRequest.ContentType = "application/x-www-form-urlencoded";
  14. webRequest.Method = "POST";
  15. byte[] bytes = Encoding.ASCII.GetBytes (parameters);
  16. Stream os = null;
  17. try
  18. { // send the Post
  19. webRequest.ContentLength = bytes.Length; //Count bytes to send
  20. os = webRequest.GetRequestStream();
  21. os.Write (bytes, 0, bytes.Length); //Send it
  22. }
  23. catch (WebException ex)
  24. {
  25. MessageBox.Show ( ex.Message, "HttpPost: Request error",
  26. MessageBoxButtons.OK, MessageBoxIcon.Error );
  27. }
  28. finally
  29. {
  30. if (os != null)
  31. {
  32. os.Close();
  33. }
  34. }
  35. try
  36. { // get the response
  37. WebResponse webResponse = webRequest.GetResponse();
  38. if (webResponse == null)
  39. { return null; }
  40. StreamReader sr = new StreamReader (webResponse.GetResponseStream());
  41. return sr.ReadToEnd ().Trim ();
  42. }
  43. catch (WebException ex)
  44. {
  45. MessageBox.Show ( ex.Message, "HttpPost: Response error",
  46. MessageBoxButtons.OK, MessageBoxIcon.Error );
  47. }
  48. return null;
  49. } // end HttpPost

comments powered by Disqus