HttpHelper.cs 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. using BHJD.DBdll.Public;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using System.Net;
  6. using System.Text;
  7. public class HttpHelper : IHttpHelper
  8. {
  9. public Action<string> m_OnShowRequestAddr = null;
  10. public override string Request(HttpCmd type, object param)
  11. {
  12. HttpCmd cmd = type;
  13. switch (cmd.m_RequestType)
  14. {
  15. case HttpRequestType.GET:
  16. return HttpGet(type, param as List<string>);
  17. case HttpRequestType.POST:
  18. return HttpPost(type, param as string);
  19. default:
  20. return string.Empty;
  21. }
  22. }
  23. public override string HttpGet(HttpCmd type, List<string> paramList)
  24. {
  25. string url = type.m_Addr + "?";
  26. var kVar = type.m_Args.GetEnumerator();
  27. int index = 0;
  28. while (kVar.MoveNext())
  29. {
  30. url += kVar.Current + "=" + paramList[index];
  31. if (index < type.m_Args.Count - 1)
  32. {
  33. url += "&";
  34. }
  35. index++;
  36. }
  37. if (m_OnShowRequestAddr != null)
  38. {
  39. m_OnShowRequestAddr(url);
  40. }
  41. //Debug.Log(url);
  42. var request = (HttpWebRequest)WebRequest.Create(url);
  43. request.Method = "GET";
  44. request.ContentType = "application/json;charset=UTF-8";//ContentType
  45. var response = (HttpWebResponse)request.GetResponse();
  46. var responseString = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("utf-8")).ReadToEnd();
  47. return responseString.ToString();
  48. }
  49. public override string HttpPost(HttpCmd type, string jsonStr)
  50. {
  51. string url = type.m_Addr;
  52. var request = (HttpWebRequest)WebRequest.Create(url);
  53. request.Method = "POST";
  54. request.ContentType = "application/json;charset=UTF-8";//ContentType
  55. byte[] byteData = Encoding.UTF8.GetBytes(jsonStr);
  56. int length = byteData.Length;
  57. request.ContentLength = length;
  58. if (m_OnShowRequestAddr != null)
  59. {
  60. m_OnShowRequestAddr(url);
  61. }
  62. Stream writer = request.GetRequestStream();
  63. writer.Write(byteData, 0, length);
  64. writer.Close();
  65. var response = (HttpWebResponse)request.GetResponse();
  66. var responseString = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("utf-8")).ReadToEnd();
  67. return responseString.ToString();
  68. }
  69. }