Unity:使用JSON使用WWW类对RESTful API发出POST请求

时间:2016-06-30 00:00:03

标签: c# rest post unity3d

enter image description here

我正在尝试在Unity脚本中发出POST请求。标题应包含密钥'内容类型'设置为' application / json'。输入键是"电子邮件"。

所以这是我的剧本:

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:错误请求。你如何正确地创建一个POST请求?

1 个答案:

答案 0 :(得分:0)

如果您在网络调试器中检查您的请求(或使用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;
    }
}