HttpHelper.cs 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.IO.Compression;
  5. using System.Net;
  6. using System.Net.Security;
  7. using System.Security.Cryptography.X509Certificates;
  8. using System.Text;
  9. using System.Text.RegularExpressions;
  10. using System.Threading.Tasks;
  11. namespace SCC.Common
  12. {
  13. /// <summary>
  14. /// Http连接操作帮助类
  15. /// </summary>
  16. public class HttpHelper
  17. {
  18. public string PostJson(Dictionary<string, string> dic,string url)
  19. {
  20. try
  21. {
  22. string result = "";
  23. HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
  24. req.Method = "POST";
  25. req.ContentType = "application/x-www-form-urlencoded";
  26. #region 添加Post 参数
  27. StringBuilder builder = new StringBuilder();
  28. int i = 0;
  29. foreach (var item in dic)
  30. {
  31. if (i > 0)
  32. builder.Append("&");
  33. builder.AppendFormat("{0}={1}", item.Key, item.Value);
  34. i++;
  35. }
  36. byte[] data = Encoding.UTF8.GetBytes(builder.ToString());
  37. req.ContentLength = data.Length;
  38. using (Stream reqStream = req.GetRequestStream())
  39. {
  40. reqStream.Write(data, 0, data.Length);
  41. reqStream.Close();
  42. }
  43. #endregion
  44. HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
  45. Stream stream = resp.GetResponseStream();
  46. //获取响应内容
  47. using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
  48. {
  49. result = reader.ReadToEnd();
  50. }
  51. return result;
  52. }
  53. catch (Exception e)
  54. {
  55. return "";
  56. }
  57. }
  58. }
  59. }