带有JSON请求的Unity 3d呼叫发布API [英] Unity 3d call post api with json request

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

问题描述

我想在Unity 3d中使用两个json参数用户名和密码来调用登录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);
        }
    }

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

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

请帮助.

推荐答案

您需要手动设置消息的内容标头和正文,并将表单数据字符串转换为json字符串并将参数参数发送到CallLogin :

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 (www.error != null)
    {
        Debug.Log("Erro: " + www.error);
    }
    else
    {
        Debug.Log("All OK");
        Debug.Log("Status Code: " + request.responseCode);
    }

}

这篇关于带有JSON请求的Unity 3d呼叫发布API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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