当前位置:   article > 正文

Unity C# 之 使用 HttpWebRequest 基础知识/HttpWebRequest 进行异步Post 网络访问/数据流形式获取数据(Task/async/await)的代码简单实现_unitywebrequest 异步

unitywebrequest 异步

Unity C# 之 使用 HttpWebRequest 基础知识/HttpWebRequest 进行异步Post 网络访问/数据流形式获取数据(Task/async/await)的代码简单实现

目录

Unity C# 之 使用 HttpWebRequest 基础知识/HttpWebRequest 进行异步Post 网络访问/数据流形式获取数据(Task/async/await)的代码简单实现

一、简单介绍

二、实现原理

三、注意事项

四、效果预览

五、关键代码

附录 : HttpWebRequest 的一些基础知识

1、HttpWebRequest 常用属性

2、HttpWebRequest  中的 ContentType

3、HttpWebRequest 一般使用示例

4、HttpWebRequest  json 文本 Post 请求示例

5、 HttpWebRequest   multipart/form-data 文件上传示例


一、简单介绍

Unity 在开发中,网络访问:

  • 可以使用 UnityWebRequest 访问,不过好似只能用协程的方式,并且访问只能在主线程中;
  • 所以这里使用 C# 中的 HttpWebRequest,进行网络访问,而且 HttpWebRequest,允许在子线程中访问,在一些情况下可以大大减少主线程的网络访问压力; 

这里使用 HttpWebRequest ,进行 Post 访问,并且Task 结合 async (await) 的进行异步访问,最后使用 Stream 流式的形式获取数据,在这里做一个简单的记录,以便后期使用的时候参考。

二、实现原理

1、HttpWebRequest 创建 post 的请求

2、GetRequestStreamAsync 发起 异步请求

3、GetResponseAsync 和 GetResponseStream 异步获取响应数据流

4、因为使用到异步,所以 async Task<string> 返回异步获取的流数据

三、注意事项

1、获取更新的流数据打印是,注意 每次更新下 buffer ,不然输出打印的结果可能不是预期的

  1. // 循环获取流式数据
  2. while ((bytesRead = await reader.ReadAsync(buffer, 0, buffer.Length)) > 0)
  3. {
  4. sb.Append(buffer, 0, bytesRead);
  5. Console.WriteLine(buffer);
  6. buffer = new char[1024];
  7. }

四、效果预览

五、关键代码

  1. using System;
  2. using System.Net;
  3. using System.Text;
  4. namespace TestHttpWebRequestPostStream
  5. {
  6. internal class Program
  7. {
  8. static string m_Authorization = "Your_Authorization";
  9. static int TIMEOUT_TIME = 10000; // 超时时间
  10. static async Task Main(string[] args)
  11. {
  12. string url = "Your_STREAM_URL";
  13. string postData = "Your_POST_DATA";
  14. string content = await PostRequestStreamToStringAsync(url, postData);
  15. Console.WriteLine("Response content:");
  16. Console.WriteLine(content);
  17. }
  18. static async Task<string> PostRequestStreamToStringAsync(string url, string postData)
  19. {
  20. try
  21. {
  22. HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
  23. request.ReadWriteTimeout = TIMEOUT_TIME;
  24. request.Timeout = TIMEOUT_TIME;
  25. request.Method = "POST";
  26. request.ContentType = "application/json"; // 根据需要设定
  27. request.Headers.Add("user-token", "xxxxxxxx"); // 根据需要设定
  28. request.Headers.Add("xxxx-authorization", m_Authorization); // 根据需要设定
  29. //流式发起请求
  30. using (Stream requestStream = await request.GetRequestStreamAsync())
  31. {
  32. byte[] dataBytes = Encoding.UTF8.GetBytes(postData);
  33. await requestStream.WriteAsync(dataBytes, 0, dataBytes.Length);
  34. }
  35. // 流式获取数据响应
  36. using (HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync())
  37. using (Stream responseStream = response.GetResponseStream())
  38. using (StreamReader reader = new StreamReader(responseStream))
  39. {
  40. StringBuilder sb = new StringBuilder();
  41. char[] buffer = new char[1024];
  42. int bytesRead;
  43. // 循环获取流式数据
  44. while ((bytesRead = await reader.ReadAsync(buffer, 0, buffer.Length)) > 0)
  45. {
  46. sb.Append(buffer, 0, bytesRead);
  47. Console.WriteLine(buffer);
  48. buffer = new char[1024];
  49. }
  50. return sb.ToString();
  51. }
  52. }
  53. catch (Exception e)
  54. {
  55. return e.Message;
  56. }
  57. }
  58. }
  59. }

附录 : HttpWebRequest 的一些基础知识

1、HttpWebRequest 常用属性

  • AllowAutoRedirect:获取或设置一个值,该值指示请求是否应跟随重定向响应。
  • CookieContainer:获取或设置与此请求关联的cookie。
  • Credentials:获取或设置请求的身份验证信息。
  • KeepAlive:获取或设置一个值,该值指示是否与 Internet 资源建立持久性连接。
  • MaximumAutomaticRedirections:获取或设置请求将跟随的重定向的最大数目。
  • Proxy:获取或设置请求的代理信息。
  • SendChunked:获取或设置一个值,该值指示是否将数据分段发送到 Internet 资源。
  • Timeout:获取或设置请求的超时值。
  • UserAgent:获取或设置 User-agent HTTP 标头的值
  • ContentType:Http内容类型
  • Headers:指定组成 HTTP 标头的名称/值对的集合。
     

2、HttpWebRequest  中的 ContentType

  • 普通文本: “text/plain”
  • JSON字符串: “application/json”
  • 数据流类型(文件流): “application/octet-stream”
  • 表单数据(键值对): “application/x-www-form-urlencoded”
  • 多分部数据: “multipart/form-data”
     

3、HttpWebRequest 一般使用示例

  1. //创建HttpWeb请求
  2. HttpWebRequest request = (HttpWebRequest)WebRequest.Create (url);
  3. //创建HttpWeb相应
  4. HttpWebResponse response = (HttpWebResponse)request.GetResponse ();
  5. Console.WriteLine ("Content length is {0}", response.ContentLength);
  6. Console.WriteLine ("Content type is {0}", response.ContentType);
  7. //获取response的流
  8. Stream receiveStream = response.GetResponseStream ();
  9. //使用streamReader读取流数据
  10. StreamReader readStream = new StreamReader (receiveStream, Encoding.UTF8);
  11. Console.WriteLine ("Response stream received.");
  12. Console.WriteLine (readStream.ReadToEnd ());
  13. response.Close ();
  14. readStream.Close ();

4、HttpWebRequest  json 文本 Post 请求示例

使用application/json作为请求头,用来告诉服务端消息主体是序列化的JSON字符串。

  1. /*
  2. * url:POST请求地址
  3. * postData:json格式的请求报文,例如:{"key1":"value1","key2":"value2"}
  4. */
  5. public static string PostUrl(string url, string postData)
  6. {
  7. HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
  8. req.Method = "POST";
  9. req.TimeOut = "800";//设置请求超时时间,单位为毫秒
  10. req.ContentType = "application/json";
  11. byte[] data = Encoding.UTF8.GetBytes(postData);
  12. req.ContentLength = data.Length;
  13. using (Stream reqStream = req.GetRequestStream())
  14. {
  15. reqStream.Write(data, 0, data.Length);
  16. reqStream.Close();
  17. }
  18. HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
  19. Stream stream = resp.GetResponseStream();
  20. //获取响应内容
  21. string result = "";
  22. using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
  23. {
  24. result = reader.ReadToEnd();
  25. }
  26. return result;
  27. }

5、 HttpWebRequest   multipart/form-data 文件上传示例

使用multipart/form-data作为请求头,用来告诉服务器消息主体是 多发文件 格式

multipart/form-data格式使用一长串字符作为boundtry封装线对字段进行分割。这也很符合multipart多个部分的语义,包含了多个部分集,每一部分都包含了一个content-desposition头,其值为form-data,以及一个name属性,其值为表单的字段名,文件输入框还可以使用filename参数指定文件名。content-type非必须属性,其值会根据文件类型进行变化,默认值是text/plain。multipart的每一个part上方是边界线,最后一个part的下方添加一个边界线。

  1. /// <summary>
  2. /// 上传文件请求
  3. /// </summary>
  4. /// <param name="url">Url</param>
  5. /// <param name="filePath">文件路径</param>
  6. /// <param name="formDatas">表单数据(字典格式)</param>
  7. /// <param name="callback">上传回调</param>
  8. public static void UploadRequest(string url, string filePath, Dictionary<string,string> formDatas, Action<string> callback)
  9. {
  10. // 时间戳,用做boundary
  11. string timeStamp = DateTime.Now.Ticks.ToString("x");
  12. //根据uri创建HttpWebRequest对象
  13. HttpWebRequest httpReq = (HttpWebRequest) WebRequest.Create(new Uri(url));
  14. httpReq.Method = "POST";
  15. httpReq.AllowWriteStreamBuffering = false; //对发送的数据不使用缓存
  16. httpReq.Timeout = 300000; //设置获得响应的超时时间(300秒)
  17. httpReq.ContentType = "multipart/form-data; boundary=" + timeStamp;
  18. //读取file文件
  19. FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
  20. BinaryReader binaryReader = new BinaryReader(fileStream);
  21. //表单信息
  22. string boundary = "--" + timeStamp;
  23. string form = "";
  24. string formFormat = boundary + "\r\nContent-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}\r\n";
  25. string formEnd = boundary + "\r\nContent-Disposition: form-data; name=\"{0}\"; filename=\"{1}\";\r\nContent-Type:application/octet-stream\r\n\r\n";
  26. foreach (var pair in formDatas)
  27. {
  28. form += string.Format(formFormat, pair.Key, pair.Value);
  29. }
  30. form += string.Format(formEnd,"file", Path.GetFileName(filePath));
  31. byte[] postHeaderBytes = Encoding.UTF8.GetBytes(form);
  32. //结束边界
  33. byte[] boundaryBytes = Encoding.ASCII.GetBytes("\r\n--" + timeStamp + "--\r\n");
  34. long length = fileStream.Length + postHeaderBytes.Length + boundaryBytes.Length;
  35. httpReq.ContentLength = length; //请求内容长度
  36. try
  37. {
  38. //每次上传4k
  39. int bufferLength = 4096;
  40. byte[] buffer = new byte[bufferLength];
  41. //已上传的字节数
  42. long offset = 0;
  43. int size = binaryReader.Read(buffer, 0, bufferLength);
  44. Stream postStream = httpReq.GetRequestStream();
  45. //发送请求头部消息
  46. postStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);
  47. while (size > 0)
  48. {
  49. postStream.Write(buffer, 0, size);
  50. offset += size;
  51. size = binaryReader.Read(buffer, 0, bufferLength);
  52. }
  53. //添加尾部边界
  54. postStream.Write(boundaryBytes, 0, boundaryBytes.Length);
  55. postStream.Close();
  56. //获取服务器端的响应
  57. using (HttpWebResponse response = (HttpWebResponse) httpReq.GetResponse())
  58. {
  59. Stream receiveStream = response.GetResponseStream();
  60. StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8);
  61. string returnValue = readStream.ReadToEnd();
  62. Debug.Log("upload result:"+returnValue);
  63. callback?.Invoke(returnValue);
  64. response.Close();
  65. readStream.Close();
  66. }
  67. }
  68. catch (Exception ex)
  69. {
  70. Debug.Log("文件传输异常: " + ex.Message);
  71. }
  72. finally
  73. {
  74. fileStream.Close();
  75. binaryReader.Close();
  76. }
  77. }

Unity 上的简单的异步封装使用

1、HttpWebRequest 异步 Post 获取数据

  1. using System;
  2. using System.IO;
  3. using System.Net;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using UnityEngine;
  7. public class GptNormalWrapper : Singleton<GptNormalWrapper>, IGptHttpWebRequestWrapper
  8. {
  9. const string GPT_URL = "Your_URL";
  10. const string AUTHORIZATION = "Your_AUTHORIZATION";
  11. const string USER_TOKEN = "123456";
  12. const int TIMEOUT_TIME = 10000; // 超时时间
  13. public string GptUrl => GPT_URL;
  14. public async Task<string> PostRequestToStringAsync(string postData) {
  15. return await PostRequestToStringAsync(GptUrl, postData);
  16. }
  17. public async Task<string> PostRequestToStringAsync(string url, string postData)
  18. {
  19. try
  20. {
  21. HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
  22. request.ReadWriteTimeout = TIMEOUT_TIME;
  23. request.Timeout = TIMEOUT_TIME;
  24. request.Method = "POST";
  25. request.ContentType = "application/json";
  26. request.Headers.Add("user-token", USER_TOKEN);
  27. request.Headers.Add("xxx-authorization", AUTHORIZATION);
  28. Debug.Log("[GptNormalWrapper] PostRequestToStringAsync msg = " + postData);
  29. byte[] jsonBytes = Encoding.UTF8.GetBytes(postData);
  30. request.ContentLength = jsonBytes.Length;
  31. Stream strStream = request.GetRequestStream();
  32. strStream.Write(jsonBytes, 0, jsonBytes.Length);
  33. strStream.Close();
  34. HttpWebResponse respone = (HttpWebResponse)await request.GetResponseAsync();
  35. Stream ns = respone.GetResponseStream();
  36. string responseContent = new StreamReader(ns, Encoding.UTF8).ReadToEnd();
  37. Debug.Log("[GptNormalWrapper] PostRequestToStringAsync 消息返回:" + responseContent);
  38. MessageBack textback = JsonUtility.FromJson<MessageBack>(responseContent);
  39. Debug.Log($"[GptNormalWrapper] PostRequestToStringAsync answer content {textback.data.choices[0].message.content} ");
  40. return new(textback.data.choices[0].message.content);
  41. }
  42. catch (Exception e)
  43. {
  44. Debug.LogError("[GptNormalWrapper] PostRequestToStringAsync error:" + e);
  45. }
  46. return new(GptChatCommonStringDefine.GPT_REQUEST_SERVER_FAILED);
  47. }
  48. }

2、HttpWebRequest 异步 Post 流式的获取数据

  1. using System.Net;
  2. using System.Threading.Tasks;
  3. using System.Text;
  4. using System.IO;
  5. using UnityEngine;
  6. using System;
  7. public class GptStreamWrapper : Singleton<GptStreamWrapper>, IGptHttpWebRequestWrapper
  8. {
  9. const string GPT_URL = "Your_URL";
  10. const string AUTHORIZATION = "Your_AUTHORIZATION";
  11. const string USER_TOKEN = "123456";
  12. const int TIMEOUT_TIME = 10000; // 超时时间
  13. public string GptUrl { get; } = GPT_URL;
  14. public async Task<string> PostRequestToStringAsync(string postData) {
  15. return await PostRequestToStringAsync(GptUrl, postData);
  16. }
  17. public async Task<string> PostRequestToStringAsync(string url, string postData)
  18. {
  19. try
  20. {
  21. HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
  22. request.ReadWriteTimeout = TIMEOUT_TIME;
  23. request.Timeout = TIMEOUT_TIME;
  24. request.Method = "POST";
  25. request.ContentType = "application/json";
  26. request.Headers.Add("user-token", USER_TOKEN);
  27. request.Headers.Add("xxx-authorization", AUTHORIZATION);
  28. //流式发起请求
  29. using (Stream requestStream = await request.GetRequestStreamAsync())
  30. {
  31. Debug.Log("[GptStreamWrapper] PostRequestStreamToStringAsync postData : " + postData);
  32. byte[] dataBytes = Encoding.UTF8.GetBytes(postData);
  33. await requestStream.WriteAsync(dataBytes, 0, dataBytes.Length);
  34. }
  35. // 流式获取数据响应
  36. using (HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync())
  37. using (Stream responseStream = response.GetResponseStream())
  38. using (StreamReader reader = new StreamReader(responseStream))
  39. {
  40. StringBuilder sb = new StringBuilder();
  41. char[] buffer = new char[1024];
  42. int bytesRead;
  43. // 循环获取流式数据
  44. while ((bytesRead = await reader.ReadAsync(buffer, 0, buffer.Length)) > 0)
  45. {
  46. sb.Append(buffer, 0, bytesRead);
  47. Debug.Log("[GptStreamWrapper] PostRequestStreamToStringAsync getting steam data : " + buffer);
  48. buffer = new char[1024];
  49. }
  50. Debug.Log("[GptStreamWrapper] PostRequestStreamToStringAsync whole stream data : " + sb.ToString());
  51. return sb.ToString();
  52. }
  53. }
  54. catch (Exception e)
  55. {
  56. Debug.Log("[GptStreamWrapper] PostRequestStreamToStringAsync Exception Message data : " + e.Message);
  57. return new(GptChatCommonStringDefine.GPT_REQUEST_SERVER_FAILED);
  58. }
  59. }
  60. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/weixin_40725706/article/detail/748410
推荐阅读
相关标签
  

闽ICP备14008679号