问题
I am using UnityWebRequest to POST a string on the JSON that is accessible online. Unfortunately I am getting HTTP/1.1 405 Method Not Allowed
error in Unity. It is definitely not the API key error otherwise I would get unauthorized message.
I have seen some examples where PUT was used instead of POST, so I am not sure if what I am doing for POST here is right or not. Kindly help me out.
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",
}
回答1:
Still just a guess but easier to explain what I mean here ^^
You probably have to use 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!");
}
}
}
Or as mentioned before you might also be able to follow this post and use Post
but without a form but directly using raw data
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();
来源:https://stackoverflow.com/questions/64101302/http-method-not-allowed-in-rest-api-post