我目前正在尝试使用 Trello Rest API 将 Trello 集成到 Unity 中。我能够显示给定的板及其列表和卡片。到目前为止没有问题。但一旦我尝试创建或更新卡片,我就会收到未经授权的异常。我的令牌具有写入权限,当我通过 ReqBin Curl 测试器运行命令时,该命令一切正常,卡将添加到板上。但是 HTTP 请求给了我未经授权的错误。
有效的curl命令
curl -X POST https://api.trello.com/1/cards?idList={id_list}&key={app_key}&token={app_token} -d '{"name":"TestCard","desc":"description"}' --header "Content-Type: application/json"
HTTP-Request 函数(数据当前是空字符串,因为我当前正在尝试将数据添加到 url)
private static async Task<bool> SendTrelloPostHttpRequest(string url, string data) {
Debug.Log(url);
using (var httpClient = new HttpClient()) {
using (var request = new HttpRequestMessage(System.Net.Http.HttpMethod.Post, url)) {
HttpResponseMessage response = await httpClient.PostAsync(url, new StringContent(data));
if (!response.IsSuccessStatusCode) {
Debug.LogError("Failed " + response.StatusCode);
return false;
} else {
Debug.Log("Sucessfully " + response.Content.ToString());
return true;
}
}
}
这是我用来运行请求的 url
string url = $"{_trelloAPI}cards?idList={listId}&key={_trelloAppKey}&token={_trelloAppToken} -d '{{\"name\":\"{card.Name}\",\"desc\":\"{card.Desc}\"}}\' --header \"Content-Type: application/json\"";
我不知道为什么curl请求有效而http请求无效,我仔细检查了所有内容,但我找不到任何错误
我自己解决了^^
Http请求函数现在看起来像这样
private static async Task<bool> TrelloHttpPostRequest(string url, string data) {
Debug.Log("Post request - " + url);
try {
using (var httpClient = new HttpClient()) {
HttpContent content = new StringContent(data, System.Text.Encoding.UTF8, "application/json");
HttpResponseMessage response = await httpClient.PostAsync(url, content);
if (!response.IsSuccessStatusCode) {
Debug.LogError($"HTTP Post failed ({response.Content.ToString()}) {response.StatusCode}");
return false;
} else {
Debug.Log("HTTP Post sucessfully " + response.Content.ToString());
return true;
}
}
} catch (System.Exception e) {
Debug.LogError(e.Message.ToString());
return false;
}
}
现在不再需要将有效负载作为 url 的一部分。这是新网址
string url = $"{_trelloAPI}cards?idList={card.IdList}&key={_trelloAppKey}&token={_trelloAppToken}";
所以仍然不确定为什么响应是 (401) 未经授权,但使用此代码和 url 就可以正常工作了。