1

我在從Unity3D遊戲引擎向我的firebase雲功能項目發出POST Http請求時遇到了一些麻煩。UnityWebRequest HTTP POST到Firebase雲功能

我不斷收到一個代碼400的響應,並在火力控制檯,我可以看到以下錯誤:

Error: invalid json at parse

我真的沒有很多知識有關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":"fake-guid","rating":"-1"}

這裏是我當前在firebase函數中部署的函數。

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!'); 
    } 
}); 

有沒有人試過這個,併成功之前?

在此先感謝!

回答

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)); 
    } 

最好!