[英]Unity: POST request to RESTful APIs using WWW class using JSON
我试图在Unity脚本中发出POST请求。 标头应包含设置为“ application / json”的键“ Content-Type”。 输入键是“电子邮件”。
所以这是我的脚本:
private static readonly string POSTWishlistGetURL = "http://mongodb-serverURL.com/api/WishlistGet";
public WWW POST()
{
WWWForm form = new WWWForm();
form.AddField("email", "abcdd@gmail.com");
Dictionary<string, string> postHeader = form.headers;
if (postHeader.ContainsKey("Content-Type"))
postHeader["Content-Type"] = "application/json";
else
postHeader.Add("Content-Type", "application/json");
WWW www = new WWW(POSTWishlistGetURL, form.data, postHeader);
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);
}
}
我一直在获取数据。错误= 400:错误的请求。 您如何正确创建POST请求?
如果在Web调试器中检查请求(或使用诸如RequestBin之类的在线检查网站),则会看到当前正在发布以下请求正文:
email=abcdd%40gmail.com
那不是该服务所期望的。 正如您在文档和示例CURL请求中所看到的,它希望您发送以下JSON内容:
{"email": "abcdd@gmail.com"}
Unity提供了一个不错的便捷类JsonUtility来生成JSON数据,但它需要一个适当的类来定义您的结构。 结果代码将如下所示:
// Helper object to easily serialize json data.
public class WishListRequest {
public string email;
}
public class MyMonoBehavior : MonoBehaviour {
...
private static readonly string POSTWishlistGetURL = "...bla...";
public WWW Post()
{
WWWForm form = new WWWForm();
// Create the parameter object for the request
var request = new WishListRequest { email = "abcdd@gmail.com" };
// Convert to JSON (and to bytes)
string jsonData = JsonUtility.ToJson(request);
byte[] postData = System.Text.Encoding.ASCII.GetBytes(jsonData);
Dictionary<string, string> postHeader = form.headers;
if (postHeader.ContainsKey("Content-Type"))
postHeader["Content-Type"] = "application/json";
else
postHeader.Add("Content-Type", "application/json");
WWW www = new WWW(POSTWishlistGetURL, postData, postHeader);
StartCoroutine(WaitForRequest(www));
return www;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.