You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

67 lines
3.1 KiB

1 year ago
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. namespace ICSSoft.Common
  7. {
  8. public class HTTPHelper
  9. {
  10. private static log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
  11. //public static string HttpPost(string apiName, string url, string body)
  12. //{
  13. // try
  14. // {
  15. // //log.Debug(url + Environment.NewLine + body);
  16. // Encoding encoding = Encoding.UTF8;
  17. // System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
  18. // request.Method = "POST";
  19. // request.Accept = "application/json, text/javascript, */*"; //"text/html, application/xhtml+xml, */*";
  20. // request.ContentType = "application/json; charset=utf-8";
  21. // // request.ContentType = "text/html, application/xhtml+xml";
  22. // byte[] buffer = encoding.GetBytes(body);
  23. // request.ContentLength = buffer.Length;
  24. // request.GetRequestStream().Write(buffer, 0, buffer.Length);
  25. // System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse();
  26. // using (System.IO.StreamReader reader = new System.IO.StreamReader(response.GetResponseStream(), encoding))
  27. // {
  28. // return reader.ReadToEnd();
  29. // }
  30. // }
  31. // catch (System.Net.WebException ex)
  32. // {
  33. // log.Error(ex.ToString() + Environment.NewLine + url + Environment.NewLine + body);
  34. // throw new Exception(apiName + "调用失败," + ex.Message);
  35. // }
  36. //}
  37. public static string HttpPost(string apiName, string url, string body)
  38. {
  39. try
  40. {
  41. Encoding encoding = Encoding.UTF8;
  42. System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
  43. request.Method = "POST";
  44. request.Accept = "application/json, text/javascript, */*";
  45. request.ContentType = "application/json; charset=utf-8";
  46. request.Timeout = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["TimeOut"]);//超时时间
  47. byte[] buffer = encoding.GetBytes(body);
  48. request.ContentLength = buffer.Length;
  49. request.GetRequestStream().Write(buffer, 0, buffer.Length);
  50. System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse();
  51. using (System.IO.StreamReader reader = new System.IO.StreamReader(response.GetResponseStream(), encoding))
  52. {
  53. return reader.ReadToEnd();
  54. }
  55. }
  56. catch (System.Net.WebException ex)
  57. {
  58. log.Error(ex.ToString() + Environment.NewLine + url + Environment.NewLine + body);
  59. throw new Exception(apiName + "调用失败," + ex.Message);
  60. }
  61. }
  62. }
  63. }