Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unity 3d call post api with json request

Tags:

c#

php

unity3d

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.

like image 828
Himanshu Shekher Jha Avatar asked Aug 02 '17 20:08

Himanshu Shekher Jha


1 Answers

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

}
like image 110
joreldraw Avatar answered Oct 24 '22 13:10

joreldraw