unity的UnityWebRequest 报错: Post Error: HTTP/1.1 415 Unsupported Media Type UnityEngine.
错误代码
private string tmp_postURL = "http://192.168.1.7:18631/postapi/test1";
private IEnumerator Test_SendPost_error()
{
UnityWebRequest request = new UnityWebRequest(tmp_postURL, "POST");
yield return request.SendWebRequest();
if (request.result == UnityWebRequest.Result.ConnectionError || request.result == UnityWebRequest.Result.ProtocolError)
{
Debug.LogError($"Post Error: {request.error}");
}
else
{
Debug.Log($"Post Success: {request.downloadHandler.text}");
}
}
报错信息:
Post Error: HTTP/1.1 415 Unsupported Media Type
UnityEngine.Debug:LogError (object)
HttpCorsTest/<Test_SendPost>d__3:MoveNext () (at Assets/Scripts/ProgramScripts/HttpCorsTest.cs:28)
UnityEngine.SetupCoroutine:InvokeMoveNext (System.Collections.IEnumerator,intptr)
解释
HTTP 415 错误表示服务器不支持请求中使用的媒体类型。通常,这是因为请求头中缺少或设置不正确的 Content-Type。
解决办法
- 设置 Content-Type
确保在请求中设置正确的 Content-Type。如果你发送的是 JSON 数据,应该设置为 application/json。 - 添加请求体
如果你要发送数据,请确保在请求中包含数据。 - 发送空数据
有时发送一个空 JSON 对象 {} 可能会解决问题。 - 如果不发送空数据,需要确认服务器可以接收空数据
修改后的代码
private string tmp_postURL = "http://192.168.1.7:18631/postapi/test1";
private IEnumerator Test_SendPost()
{
// 即使没有数据,也可以发送一个空的 JSON 对象
string jsonData = "{}";
byte[] bodyRaw = System.Text.Encoding.UTF8.GetBytes(jsonData);
UnityWebRequest request = new UnityWebRequest(tmp_postURL, "POST");
request.uploadHandler = new UploadHandlerRaw(bodyRaw);
request.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($"Post Error: {request.error}");
}
else
{
Debug.Log($"Post Success: {request.downloadHandler.text}");
}
}