HttpRequest.cs 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using System.Net;
  6. using System.Net.Http;
  7. using System.Text;
  8. using UnityEngine;
  9. using UnityEngine.UI;
  10. public static class HttpRequest
  11. {
  12. public static string SendHttpRequest(string headersData, string postData, string url, string contentType)
  13. {
  14. /* byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(postData);
  15. HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(new Uri(url));
  16. webRequest.Method = "POST";
  17. webRequest.ContentType = contentType;
  18. webRequest.ContentLength = byteArray.Length;
  19. webRequest.Headers.Add("x_auth_token", headersData);
  20. //webRequest.Timeout = 5000;
  21. Stream newStream = webRequest.GetRequestStream();
  22. newStream.Write(byteArray, 0, byteArray.Length);
  23. newStream.Close();
  24. HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
  25. StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
  26. int code = response.GetHashCode();
  27. Debug.Log("状态码:" + code);
  28. //Debug.Log("响应我的消息:" + sr.ReadToEnd());
  29. string str = sr.ReadToEnd();
  30. return str;*/
  31. try
  32. {
  33. byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(postData);
  34. HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(new Uri(url));
  35. webRequest.Method = "POST";
  36. webRequest.ContentType = contentType;
  37. webRequest.ContentLength = byteArray.Length;
  38. webRequest.Headers.Add("x_auth_token", headersData);
  39. webRequest.Timeout = 2000;
  40. Stream newStream = webRequest.GetRequestStream();
  41. newStream.Write(byteArray, 0, byteArray.Length);
  42. newStream.Close();
  43. HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
  44. StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
  45. //检验状态码,如果成功接收数据
  46. int code = response.GetHashCode();
  47. Debug.Log("code: " + code);
  48. /* if (code == 200)
  49. {*/
  50. string str = sr.ReadToEnd();
  51. Debug.Log("str: " + str);
  52. webRequest.Abort();
  53. response.Close();
  54. sr.Close();
  55. return str;
  56. /* }*/
  57. }
  58. catch (Exception e)
  59. {
  60. e.ToString();
  61. Debug.Log("e: " + e.ToString());
  62. return null;
  63. }
  64. }
  65. }