简体   繁体   English

带有 json 请求的 Unity 3d 调用 post api

[英]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.我想使用两个json参数用户名和密码在unity 3d中调用登录api。

I followed many post available on stackoverflow.我关注了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.如果我从我的 android 应用程序和邮递员和 chorome 调用这个 api,它在那里工作正常。

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.所以我的问题是如何在 unity 3d 中使用 json 请求调用 post api。

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 :您需要手动设置内容标题和消息正文,并将表单数据字符串转换为 json 字符串并将 how 参数发送到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);
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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