我尝试将OAuth2不记名令牌和Post请求传递到我的服务器(使用Google Apps脚本执行API)。我尝试设置授权令牌的任何方式都会导致401未经授权的错误。我确定我以某种方式设置错误,但我一直无法弄清楚错误。
以下是我目前的代码。
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;
}
}
我尝试在实际的Data对象中设置标题,但也没有运气。
答案 0 :(得分:0)
尝试enconding到UTF8,将UploadHandleRaw更改为UploadHandle并将请求设置为单个帖子:
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", "POST");
UploadHandler uploadHandler =(UploadHandler) new UploadHandlerRaw(Encoding.UTF8.GetBytes(data.toJsonString()));
request.uploadHandler = uploadHandler;
request.downloadHandler = new DownloadHandlerBuffer();
request.SetRequestHeader("Content-Type", "application/json");
request.SetRequestHeader("Authorization", "Bearer " + DriveAPI.getInstance().getAuthToken());
yield return request.Send();
if (www.error != null)
{
Debug.Log("Error: " + www.error);
}
else
{
Debug.Log("Status Code: " + request.responseCode);
}
}
答案 1 :(得分:0)
原来我的代码工作正常。
来自Apps脚本的错误消息在发送Auth令牌时具有误导性。我能够通过从我的脚本(为Execution API端点提供服务)生成一个auth令牌并在我的应用程序中对该令牌进行硬编码来测试正确性。这样做会导致请求成功。
我已经检查过脚本和我的应用中使用的云项目是否相同,但仍然收到错误,但这是另一个问题的问题:)。