简体   繁体   中英

Unity: POST request to RESTful APIs using WWW class using JSON

在此处输入图片说明

I am trying to make a POST request in Unity script. The header should contain the key 'Content-Type' that is set to 'application/json'. The input key is "email".

So here's my script:

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

I keep getting data.error = 400: Bad Request. How do you properly create a POST request?

If you inspect your request in a web debugger (or use an online inspection website like RequestBin ), you'll see that you are currently posting the following request body:

email=abcdd%40gmail.com

That is not what that service is expecting. As you can see in the documentation and the example CURL request, it wants you to send the following JSON content:

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

Unity offers a nice convenience class to generate JSON data, JsonUtility , but it requires a proper class defining your structure. The resulting code will something like this:

// 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;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM