9

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.

3
  • We do it all the time. You might flesh out how you're creating the request, the code should not be very long, and how you're receiving it on the server side. Commented Aug 2, 2017 at 20:28
  • Please post your code. Also post the json or request that you got to work with postman. This will help determine where things went bad.
    – Programmer
    Commented Aug 2, 2017 at 22:20
  • @RetiredNinja : Please check my code, I am using this method to call API. You can username "yogi" and password "himanshu". Commented Aug 3, 2017 at 5:07

1 Answer 1

24

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

}
1
  • Should be marked as answer. Works wonderfully :) Thanks a lot bud
    – Tayab
    Commented Jan 23, 2023 at 13:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.