在 Unity 中使用 UnityWebRequest 类来向 C# HttpListener 发送 POST 请求,并将 Word 文档作为数据附加到请求中,C# HttpListener接受并且保存到本地
时间: 2024-01-21 21:16:23 浏览: 131
以下是在 Unity 中使用 UnityWebRequest 类向 C# HttpListener 发送 POST 请求,并将 Word 文档作为数据附加到请求中,C# HttpListener接受并且保存到本地的示例代码:
UnityWebRequest 请求:
```csharp
IEnumerator PostWordDocument(string url, string filePath)
{
byte[] data = File.ReadAllBytes(filePath);
UnityWebRequest request = UnityWebRequest.Post(url, "POST");
request.uploadHandler = new UploadHandlerRaw(data);
request.SetRequestHeader("Content-Type", "application/octet-stream");
yield return request.SendWebRequest();
if (request.result == UnityWebRequest.Result.Success)
{
Debug.Log("Post Word document succeeded!");
}
else
{
Debug.Log("Post Word document failed: " + request.error);
}
}
```
C# HttpListener 接受和保存请求:
```csharp
HttpListener listener = new HttpListener();
listener.Prefixes.Add("http://localhost:8080/");
listener.Start();
while (true)
{
HttpListenerContext context = listener.GetContext();
HttpListenerRequest request = context.Request;
if (request.HttpMethod == "POST")
{
using (FileStream fs = new FileStream("word.docx", FileMode.Create))
{
request.InputStream.CopyTo(fs);
fs.Flush();
}
HttpListenerResponse response = context.Response;
response.StatusCode = 200;
response.StatusDescription = "OK";
response.Close();
}
}
```
其中,`PostWordDocument(string url, string filePath)` 方法中的 `url` 参数是 C# HttpListener 接收请求的地址,`filePath` 参数是要上传的 Word 文档路径。在上面的示例代码中,请求的数据是 Word 文档的二进制数据,通过 `UploadHandlerRaw` 类型的 `uploadHandler` 属性附加到了请求中。在 C# HttpListener 接受请求后,通过 `request.InputStream` 获取请求的数据,并将其保存到本地文件中。
阅读全文