带有 json 请求的 Unity 3d 调用 post api [英] Unity 3d call post api with json request

查看:52
本文介绍了带有 json 请求的 Unity 3d 调用 post api的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用两个json参数用户名和密码在unity 3d中调用一个登录api.

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

我关注了 stackoverflow 上的许多帖子.但是我的请求参数不在服务器上.如果我从我的 android 应用程序和邮递员和 chorome 调用这个 api,它在那里工作正常.

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

所以我的问题是如何在 unity 3d 中使用 json 请求调用 post api.

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

请帮忙.

推荐答案

你需要手动设置内容头和消息正文,并将你的表单数据字符串转换为json字符串并发送how参数给呼叫登录:

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

}

这篇关于带有 json 请求的 Unity 3d 调用 post api的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆