我試圖將OAuth2載體令牌和Post請求一起傳遞給我的服務器(使用Google Apps腳本執行API)。我試圖設置授權令牌的方式不斷收到401未經授權的錯誤。我確信我會以某種方式設置它,但我一直無法弄清楚什麼是錯的。未通過UnityWebRequest傳遞授權標頭
下面是我目前的代碼。
private static UnityWebRequest createRequest(string functionName, List<string> parameters)
{
PostData data = new PostData();
data.Add("function", functionName);
data.Add("parameters", string.Join(",", parameters.ToArray()));
data.Add("devMode", "true"); // TODO: remove before launch
Debug.Log(data.toJsonString());
UnityWebRequest request = new UnityWebRequest(
"https://script.googleapis.com/v1/scripts/" + SERVER_SCRIPT_ID + ":run",
UnityWebRequest.kHttpVerbPOST);
UploadHandlerRaw uploadHandler = new UploadHandlerRaw(data.toJsonBytes());
request.uploadHandler = uploadHandler;
request.downloadHandler = new DownloadHandlerBuffer();
request.SetRequestHeader("Content-Type", "application/json; charset=utf-8");
request.SetRequestHeader("Authorization", "Bearer " + DriveAPI.getInstance().getAuthToken());
yield return request.Send();
Debug.Log(request.downloadHandler.text);
}
[Serializable]
private class PostData : Dictionary<string, string>
{
public byte[] toJsonBytes()
{
return Encoding.ASCII.GetBytes(toJsonString());
}
public string toJsonString()
{
string result = "{";
foreach (string key in this.Keys)
{
string value;
TryGetValue(key, out value);
result += "\"" + key + "\":\"" + value + "\",";
}
result = result.Substring(0, result.Length - 1) + "}";
return result;
}
}
我已經嘗試在實際的數據對象中設置標題,但沒有運氣那裏要麼。
不幸的是沒有運氣。經過一些更多的調試後,我發現這是auth令牌本身而不是請求的問題(錯誤消息非常具有誤導性)。從我的腳本生成驗證令牌並將其硬編碼到請求中會導致請求成功。所以我的問題是生成驗證碼而不是請求本身。 (我確實確保我使用的是同一個雲計劃,所以我仍在調查此問題)。 – t3jem