HttpHelper.cs 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Net;
  5. using System.Text;
  6. using WUtilitiesV01.Helper.ExceptionHelper;
  7. using WUtilitiesV01.WLogs;
  8. namespace Ips.Adc.QfCard.Cli
  9. {
  10. internal class HttpHelper
  11. {
  12. public static string Post(string ip, string typeVal, Dictionary<string, object> keyValuePairs)
  13. {
  14. try
  15. {
  16. ip = String.Format("http://{0}:8080/php/ADCard28712", ip);
  17. HttpWebRequest webrequest = WebRequest.Create(ip) as HttpWebRequest;
  18. webrequest.Method = "post";
  19. //webrequest.Headers.Add("Content-Type:application/x-www-form-urlencoded;charset=UTF-8");
  20. webrequest.ContentType = "application/x-www-form-urlencoded";
  21. var body = "type={0}&data={1}";
  22. if (keyValuePairs == null)
  23. keyValuePairs = new Dictionary<string, object>();
  24. var jsonStr = Newtonsoft.Json.JsonConvert.SerializeObject(keyValuePairs);
  25. WLog.Instance.Info(string.Format("Post:{0}\t{1}", ip, string.Format(body, typeVal, (jsonStr))));
  26. body = string.Format(body, typeVal, Uri.EscapeDataString(jsonStr));
  27. byte[] postdatabyte = Encoding.UTF8.GetBytes(body);
  28. webrequest.ContentLength = postdatabyte.Length;
  29. using (Stream stream = webrequest.GetRequestStream())
  30. {
  31. stream.Write(postdatabyte, 0, postdatabyte.Length);
  32. }
  33. using (var httpWebResponse = webrequest.GetResponse())
  34. using (StreamReader responseStream = new StreamReader(httpWebResponse.GetResponseStream()))
  35. {
  36. string ret = responseStream.ReadToEnd();
  37. return "Result:" + ret;
  38. }
  39. }
  40. catch (Exception e)
  41. {
  42. WLog.Instance.Error(e,"post结果");
  43. return "Error:" + e.Message;
  44. }
  45. }
  46. }
  47. }