我正在尝试向 Unity 中的 restful web API 发出 POST 请求。
header 将是 Content-Type: application/json
原始数据输入的一个示例是,其中数据是键,json 字符串是值:
{
"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);
}
}
如何使用带有表单和 header 的 WWW
类发送请求?或者,一般来说,我该如何发送这种发帖请求?
最佳答案
如果你想添加原始 json 数据,最好只传递它而不用 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;
}
关于c# - 统一: POST request using WWW class using JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38109658/