纽威
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.

68 lines
2.8 KiB

2 years ago
2 years ago
  1. using RestSharp;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Net;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9. namespace NFine.Data.Extensions
  10. {
  11. public class HTTPHelper
  12. {
  13. //private static log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
  14. public static string HttpPost(string apiName, string url, string body)
  15. {
  16. try
  17. {
  18. //log.Debug(url + Environment.NewLine + body);
  19. Encoding encoding = Encoding.UTF8;
  20. System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);
  21. request.Method = "POST";
  22. request.Accept = "application/json, text/javascript, */*"; //"text/html, application/xhtml+xml, */*";
  23. request.ContentType = "application/json; charset=utf-8";
  24. // request.ContentType = "text/html, application/xhtml+xml";
  25. byte[] buffer = encoding.GetBytes(body);
  26. request.ContentLength = buffer.Length;
  27. request.GetRequestStream().Write(buffer, 0, buffer.Length);
  28. System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse();
  29. using (System.IO.StreamReader reader = new System.IO.StreamReader(response.GetResponseStream(), encoding))
  30. {
  31. return reader.ReadToEnd();
  32. }
  33. }
  34. catch (System.Net.WebException ex)
  35. {
  36. //log.Error(ex.ToString() + Environment.NewLine + url + Environment.NewLine + body);
  37. throw new Exception(apiName + "调用失败," + ex.Message);
  38. }
  39. }
  40. public static string RestFulGet(string jsonParam, string url)
  41. {
  42. try
  43. {
  44. //var userName = "TEST";
  45. //var password = "12345678";
  46. //正式地址
  47. var userName = "ADVANCED";
  48. var password = "SYSTEM08";
  49. var client = new RestClient(url);
  50. client.Authenticator = new HttpBasicAuthenticator(userName, password);
  51. var request = new RestRequest(Method.POST);
  52. request.AddHeader("Accept", "application/json");
  53. request.AddHeader("Cache-Control", "no-cache");
  54. request.AddHeader("Content-Type", "application/json");
  55. request.AddParameter("application/json", jsonParam, ParameterType.RequestBody);
  56. IRestResponse response = client.Execute(request);
  57. return response.Content;
  58. }
  59. catch (Exception ex)
  60. {
  61. throw new Exception("货柜传输检验批接口调用失败," + ex.Message);
  62. }
  63. }
  64. }
  65. }