REST API中不允许使用HTTP方法 [英] HTTP Method Not Allowed in REST API Post

查看:167
本文介绍了REST API中不允许使用HTTP方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用UnityWebRequest在可在线访问的JSON上发布字符串.不幸的是,我在Unity中遇到 HTTP/1.1 405 Method Not Allowed 错误.绝对不是API密钥错误,否则我会收到未经授权的消息.

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.

我已经看到一些使用PUT而不是POST的示例,所以我不确定在这里为POST做的事情是否正确.请帮我.

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",
}

推荐答案

只是一个猜测,但更容易解释我的意思^^

Still just a guess but easier to explain what I mean here ^^

您可能必须使用 UnityWebRequest.Put

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();

这篇关于REST API中不允许使用HTTP方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆