UnityWebRequest request = UnityWebRequest.Post(url, ""); request.SetRequestHeader("videoName", videoName);videoName报错
时间: 2024-01-06 20:03:50 浏览: 121
UnityWebRequest的Post方法的第二个参数是要发送的数据,不能传空字符串。如果只需要设置请求头,可以将第二个参数改成一个空的byte数组,如下所示:
```
UnityWebRequest request = UnityWebRequest.Post(url, new byte[]{});
request.SetRequestHeader("videoName", videoName);
```
这样就不会报错了。
相关问题
var request = new UnityWebRequest(url, "POST"); byte[] bodyRaw = Encoding.UTF8.GetBytes(json); request.uploadHandler = (UploadHandler)new UploadHandlerRaw(bodyRaw); request.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer(); request.SetRequestHeader("Content-Type", "application/json"); yield return request.SendWebRequest(); if (request.result == UnityWebRequest.Result.ConnectionError || request.result == UnityWebRequest.Result.ProtocolError) { Debug.LogError(request.error); }
如果您想要在 Unity 中使用 Result 枚举类型来判断网络请求是否成功,可以使用以下代码:
```
var request = new UnityWebRequest(url, "POST");
byte[] bodyRaw = Encoding.UTF8.GetBytes(json);
request.uploadHandler = (UploadHandler)new UploadHandlerRaw(bodyRaw);
request.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer();
request.SetRequestHeader("Content-Type", "application/json");
yield return request.SendWebRequest();
if (request.isNetworkError || request.isHttpError)
{
Debug.LogError(request.error);
}
```
这段代码中使用了 `request.isNetworkError` 和 `request.isHttpError` 来判断网络请求是否成功。如果 `isNetworkError` 或 `isHttpError` 为 true,则表示发生了网络错误或 HTTP 错误,可以通过 `request.error` 获取错误信息。
// 构造请求 UnityWebRequest request = new UnityWebRequest(url, "POST"); byte[] bodyRaw = System.Text.Encoding.UTF8.GetBytes(json); request.uploadHandler = (UploadHandler)new UploadHandlerRaw(bodyRaw); request.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer(); request.SetRequestHeader("Content-Type", "application/json"); // 发送请求 yield return request.SendWebRequest(); // 处理返回结果 if (request.isNetworkError) { Debug.Log(request.error); resultText.text = request.error; }替换掉result,unity版本太老,总是报错
如果您的 Unity 版本太老,无法使用 Result 枚举类型,您可以使用以下方式替换代码中的 `request.isNetworkError`:
```
// 构造请求
UnityWebRequest request = new UnityWebRequest(url, "POST");
byte[] bodyRaw = System.Text.Encoding.UTF8.GetBytes(json);
request.uploadHandler = (UploadHandler)new UploadHandlerRaw(bodyRaw);
request.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer();
request.SetRequestHeader("Content-Type", "application/json");
// 发送请求
yield return request.Send();
// 处理返回结果
if (request.isError)
{
Debug.Log(request.error);
resultText.text = request.error;
}
```
这段代码中使用了 `request.isError` 来判断是否发生网络错误。如果 `isError` 为 true,则表示发生了网络错误,可以通过 `request.error` 获取错误信息。
阅读全文