我在使用Unity3D游戏引擎向我的firebase云功能项目发出POST Http请求时遇到了一些麻烦。
我一直收到代码400响应,在firebase控制台中我可以看到以下错误:
错误:解析时无效的json
我对Http请求并不是很了解,经过一段时间的努力寻找解决方案后,我想寻求帮助。
以下是客户端代码:
public void RateLevel(string guid, int rating)
{
RateLevelRequest rlr = new RateLevelRequest (guid, rating.ToString());
string body = rlr.ToJson ();
UnityWebRequest www = UnityWebRequest.Post("myurl", body);
www.SetRequestHeader ("Content-Type", "application/json");
StartCoroutine (MakeRequest (www));
}
/* * * * * * * * * * * * * * * * * * *
* AUXILIAR CLASS FOR HTTP REQUESTS *
* * * * * * * * * * * * * * * * * * */
[System.Serializable]
public class RateLevelRequest
{
public string guid;
public string rating;
public RateLevelRequest(string _guid, string _rating)
{
guid = _guid;
rating = _rating;
}
public string ToJson()
{
string json = JsonUtility.ToJson (this);
Debug.Log ("RateLevelRequest Json: " + json);
return json;
}
}
我可以保证json格式正确,有这样的值。
{" GUID":"假性全局唯一标识符""评价":" -1"}
这是我目前在firebase-functions中部署的函数。
exports.rate_level = functions.https.onRequest((req, res) => {
if(req.method === 'POST')
{
console.log('guid: ' + req.body.guid);
console.log('rating: ' + req.body.rating);
console.log('invented var: ' + req.body.myinvention);
if(req.body.guid && req.body.rating &&
(req.body.rating == 1 || req.body.rating == -1))
{
res.status(200).send('You are doing a post request with the right fields and values');
}
else
{
res.status(403).send('Required Fields are not Defined!')
}
}
else
{
res.status(403).send('Wrong Request Method!');
}
});
有没有人试过这个并且之前成功了?
提前致谢!
答案 0 :(得分:2)
好的,我在excellent blog entry找到了答案。
我真的不知道出了什么问题,但我改为将我的代码替换为上述文章中指出的代码,该代码有效。我会为你们其他人发布问题发布。
public void RateLevel(string guid, int rating)
{
RateLevelRequest rlr = new RateLevelRequest (guid, rating.ToString());
string body = rlr.ToJson ();
byte[] bodyRaw = new System.Text.UTF8Encoding ().GetBytes (body);
UnityWebRequest www = new UnityWebRequest("myurl", UnityWebRequest.kHttpVerbPOST);
www.uploadHandler = (UploadHandler)new UploadHandlerRaw (bodyRaw);
www.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer();
www.SetRequestHeader ("Content-Type", "application/json");
StartCoroutine (MakeRequest (www));
}
最佳!