https post

时间:2023-03-10 00:35:42
https post
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Net.Security;
  6. using System.Security.Cryptography.X509Certificates;
  7. using System.Net;
  8. using System.IO;
  9. using System.IO.Compression;
  10. using System.Text.RegularExpressions;
  11. namespace HttpWebRequestDemo
  12. {
  13. class Program
  14. {
  15. private static readonly string DefaultUserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";
  16. private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
  17. {
  18. return true; //总是接受
  19. }
  20. public static HttpWebResponse CreatePostHttpResponse(string url, IDictionary<string, string> parameters,Encoding charset)
  21. {
  22. HttpWebRequest request = null;
  23. //HTTPSQ请求
  24. ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
  25. request = WebRequest.Create(url) as HttpWebRequest;
  26. request.ProtocolVersion = HttpVersion.Version10;
  27. request.Method = "POST";
  28. request.ContentType = "application/x-www-form-urlencoded";
  29. request.UserAgent = DefaultUserAgent;
  30. //如果需要POST数据
  31. if (!(parameters == null || parameters.Count == 0))
  32. {
  33. StringBuilder buffer = new StringBuilder();
  34. int i = 0;
  35. foreach (string key in parameters.Keys)
  36. {
  37. if (i > 0)
  38. {
  39. buffer.AppendFormat("&{0}={1}", key, parameters[key]);
  40. }
  41. else
  42. {
  43. buffer.AppendFormat("{0}={1}", key, parameters[key]);
  44. }
  45. i++;
  46. }
  47. byte[] data = charset.GetBytes(buffer.ToString());
  48. using (Stream stream = request.GetRequestStream())
  49. {
  50. stream.Write(data, 0, data.Length);
  51. }
  52. }
  53. return request.GetResponse() as HttpWebResponse;
  54. }
  55. static void Main(string[] args)
  56. {
  57. string url = "https://192.168.1.101/httpOrg/create";
  58. Encoding encoding = Encoding.GetEncoding("utf-8");
  59. IDictionary<string, string> parameters = new Dictionary<string, string>();
  60. parameters.Add("authuser", "*****");
  61. parameters.Add("authpass", "*****");
  62. parameters.Add("orgkey","*****");
  63. parameters.Add("orgname", "*****");
  64. HttpWebResponse response = Program.CreatePostHttpResponse(url,parameters,encoding);
  65. //打印返回值
  66. Stream stream = response.GetResponseStream();   //获取响应的字符串流
  67. StreamReader sr = new StreamReader(stream); //创建一个stream读取流
  68. string html = sr.ReadToEnd();   //从头读到尾,放到字符串html
  69. Console.WriteLine(html);
  70. }
  71. }
  72. }