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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With