REST API文章中不允许使用HTTP方法



我正在使用UnityWebRequest在JSON上POST一个可以在线访问的字符串。不幸的是,我在Unity中遇到了HTTP/1.1 405 Method Not Allowed错误。这肯定不是API密钥错误,否则我会得到未经授权的消息。

我看到了一些使用PUT而不是POST的例子,所以我不确定我在这里为POST所做的是否正确。请帮帮我。

IEnumerator POSTURL()
{
WWWForm form = new WWWForm();
form.AddField("ID", "Lemon");
using (UnityWebRequest request = UnityWebRequest.Post("website_url", form))
{
request.SetRequestHeader("api-key", KEY);
yield return request.SendWebRequest();
if (request.isNetworkError || request.isHttpError)
{
Debug.Log(request.error);
}
else
{
Debug.Log("Form upload complete!");
}
}
}
{
"ID": "Orange",
"Category": "Fruits",
}

仍然只是猜测,但更容易解释我在这里的意思^^

您可能必须使用UnityWebRequest.Put

// You could pass these as parameters dynmically
IEnumerator POSTURL(string id, string category)
{
// This is string interpolation and will dynamically fill in the 
// id and category value
var data = Encoding.UTF8.GetBytes($"{{"ID":"{id}","Category":"{category}"}}");
using (UnityWebRequest request = UnityWebRequest.Put("website_url", data))
{
request.SetRequestHeader("api-key", KEY);
yield return request.SendWebRequest();
if (request.isNetworkError || request.isHttpError)
{
Debug.Log(request.error);
}
else
{
Debug.Log("Form upload complete!");
}
}
}

或者如前所述,您也可以关注这篇文章并使用Post,但不需要表单,而是直接使用原始数据

var data = Encoding.UTF8.GetBytes($"{{"ID":"{id}","Category":"{category}"}}");
UnityWebRequest webRequest = UnityWebRequest.Post(uri, "");
// Fix: Add upload handler and pass json as bytes array
webRequest.uploadHandler = new UploadHandlerRaw(data);
webRequest.SetRequestHeader("Content-Type", "application/json");
yield return webRequest.SendWebRequest();

最新更新