[英]Unity 3d call post api with json request
我想使用两个json参数用户名和密码在unity 3d中调用登录api。
我关注了stackoverflow上的许多帖子。 但是我的请求参数不在服务器上。 如果我从我的 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);
}
}
所以我的问题是如何在 unity 3d 中使用 json 请求调用 post api。
请帮忙。
您需要手动设置内容标题和消息正文,并将表单数据字符串转换为 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.