【问题标题】:Unity: POST request to RESTful APIs using WWW class using JSONUnity:使用 JSON 的 WWW 类对 RESTful API 的 POST 请求
【发布时间】:2016-06-30 00:00:02
【问题描述】:

我正在尝试在 Unity 脚本中发出 POST 请求。标头应包含设置为“application/json”的键“Content-Type”。输入键是“email”。

这是我的脚本:

private static readonly string POSTWishlistGetURL = "http://mongodb-serverURL.com/api/WishlistGet";
public WWW POST()
{
 WWWForm form = new WWWForm();
 form.AddField("email",  "abcdd@gmail.com");
 Dictionary<string, string> postHeader = form.headers;
 if (postHeader.ContainsKey("Content-Type"))
     postHeader["Content-Type"] = "application/json";
 else
     postHeader.Add("Content-Type", "application/json");
 WWW www = new WWW(POSTWishlistGetURL, form.data, postHeader);
 StartCoroutine(WaitForRequest(www));
 return www;
}

IEnumerator WaitForRequest(WWW data)
{
 yield return data; // Wait until the download is done
 if (data.error != null)
 {
     MainUI.ShowDebug("There was an error sending request: " + data.error);
 }
 else
 {
     MainUI.ShowDebug("WWW Request: " + data.text);
 }
}

我不断收到 data.error = 400: Bad Request。如何正确创建 POST 请求?

【问题讨论】:

标签: c# rest post unity3d


【解决方案1】:

如果您在网络调试器中检查您的请求(或使用像 RequestBin 这样的在线检查网站),您会看到您当前正在发布以下请求正文:

email=abcdd%40gmail.com

不是该服务所期望的。正如您在文档和示例 CURL 请求中所见,它希望您发送以下 JSON 内容:

{"email": "abcdd@gmail.com"} 

Unity 提供了一个很好的便利类来生成 JSON 数据,JsonUtility,但它需要一个适当的类来定义你的结构。生成的代码将如下所示:

// Helper object to easily serialize json data. 
public class WishListRequest {
    public string email;
}

public class MyMonoBehavior : MonoBehaviour {

    ...

    private static readonly string POSTWishlistGetURL = "...bla...";
    public WWW Post()
    {
        WWWForm form = new WWWForm();

        // Create the parameter object for the request
        var request = new WishListRequest { email = "abcdd@gmail.com" };

        // Convert to JSON (and to bytes)
        string jsonData = JsonUtility.ToJson(request);
        byte[] postData = System.Text.Encoding.ASCII.GetBytes(jsonData);

        Dictionary<string, string> postHeader = form.headers;
        if (postHeader.ContainsKey("Content-Type"))
            postHeader["Content-Type"] = "application/json";
        else
            postHeader.Add("Content-Type", "application/json");
        WWW www = new WWW(POSTWishlistGetURL, postData, postHeader);
        StartCoroutine(WaitForRequest(www));
        return www;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-10
    • 2016-02-13
    • 1970-01-01
    • 2013-01-30
    • 2013-05-25
    • 1970-01-01
    • 1970-01-01
    • 2015-01-26
    相关资源
    最近更新 更多