Unity:使用 WWW 类使用 JSON 的 POST 请求 [英] Unity: POST request using WWW class using JSON

查看:28
本文介绍了Unity:使用 WWW 类使用 JSON 的 POST 请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试向 Unity 中的 Restful Web API 发出 POST 请求.

I am trying to make a POST request to restful web APIs in Unity.

标题将是 Content-Type: application/json

原始数据输入的一个例子是,其中数据是键,json字符串是值:

An example of the raw data input is, where data is the key and json string is the value:

{  
   "data":{  
      "username":"name",
      "email":"email@gmail.com",
      "age_range":21,
      "gender":"male",
      "location":"california"
   }
}

这是我的脚本:

private static readonly string POSTAddUserURL = "http://db.url.com/api/addUser";
public WWW POST()
{
    WWW www;
    Hashtable postHeader = new Hashtable();
    postHeader.Add("Content-Type", "application/json");
    WWWForm form = new WWWForm();
    form.AddField("data", jsonStr);
    www = new WWW(POSTAddUserURL, form);
    StartCoroutine(WaitForRequest(www));
    return www;
}

IEnumerator WaitForRequest(WWW data)
{
    yield return data; // Wait until the download is done
    if (data.error != null)
    {
        MainUI.ShowDebug("There was an error sending request: " + data.error);
    }
    else
    {
        MainUI.ShowDebug("WWW Request: " + data.text);
    }
}

如何使用带有表单和标题的 WWW 类发送请求?或者,一般来说,我如何发送这种发布请求?

How do I send the request using WWW class with both form and header? Or, just in general, how do I send this kind of post request?

推荐答案

如果你想添加原始 json 数据,最好不带 WWWForm

If you want to add raw json data it is better to just pass it without WWWForm

public WWW POST()
{
    WWW www;
    Hashtable postHeader = new Hashtable();
    postHeader.Add("Content-Type", "application/json");

    // convert json string to byte
    var formData = System.Text.Encoding.UTF8.GetBytes(jsonStr);

    www = new WWW(POSTAddUserURL, formData, postHeader);
    StartCoroutine(WaitForRequest(www));
    return www;
}

这篇关于Unity:使用 WWW 类使用 JSON 的 POST 请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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