简体   繁体   中英

Unity 3d call post api with json request

I want to call a login api in unity 3d with two json parameter username and password.

I followed many post available on stackoverflow. But my request parameters are not going on server. If I call this api from a my android app and postman and chorome, it is working fine there.

public IEnumerator CallLogin(string username,string password)
    {
        WWWForm form = new WWWForm();
        form.AddField("username", username);
        form.AddField("password", password);

        UnityWebRequest www = UnityWebRequest.Post("/apis/login", form);
        yield return www.Send();

        if (www.error != null)
        {
            Debug.Log("Erro: " + www.error);
        }
        else
        {
            Debug.Log("All OK");
            Debug.Log("Text: " + www.downloadHandler.text);
        }
    }

So my question is how to call a post api with json request in unity 3d.

Please help.

You need to manually set the content header and the body of the message, and convert your form data string to a json string and send how parameter to CallLogin :

public IEnumerator CallLogin(string url, string logindataJsonString)
{
    var request = new UnityWebRequest (url, "POST");
    byte[] bodyRaw = Encoding.UTF8.GetBytes(logindataJsonString);
    request.uploadHandler = (UploadHandler) new UploadHandlerRaw(bodyRaw);
    request.downloadHandler = (DownloadHandler) new DownloadHandlerBuffer();
    request.SetRequestHeader("Content-Type", "application/json");
    yield return request.SendWebRequest();

    if (request.error != null)
    {
        Debug.Log("Erro: " + www.error);
    }
    else
    {
        Debug.Log("All OK");
        Debug.Log("Status Code: " + request.responseCode);
    }

}

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