我正在為 challonge.com 開發 RestSharp API 呼叫程式,但遇到了授權問題。進行 GET 呼叫時,一切正常,我可以獲得所需的資訊。但是,當嘗試 POST 呼叫時,盡管使用相同的 API 密鑰,但狀態代碼回傳為未授權。我試過在請求正文中包含密鑰并將其作為引數,但似乎都不起作用。
以下是我正在撥打的電話:
-GET:https : //api.challonge.com/v1/documents/tournaments/index
-POST:https ://api.challonge.com/v1/documents/tournaments/create
這是我的代碼。
public class APICall
{
HttpUtility http = new HttpUtility();
RestClient client = new RestClient("https://api.challonge.com/v1/");
public string GetCall(string key)
{
client.AddDefaultHeader("Content-Type", "application/json");
RestRequest request = new RestRequest("tournaments", DataFormat.Json);
request.AddParameter("api_key", key);
IRestResponse response = client.Get(request);
return response.StatusCode.ToString();
}
public string PostCall(string tournName, string key)
{
client.AddDefaultHeader("Content-Type", "application/json");
RestRequest request = new RestRequest("tournaments", DataFormat.Json);
var obj = new Tournament(tournName,key);
//request.AddParameter("api_key", key);
request.AddJsonBody(obj);
IRestResponse response = client.Post(request);
return response.StatusCode.ToString();
}
}
uj5u.com熱心網友回復:
驗證
與 API 的所有互動都需要一個具有經過驗證的電子郵件地址和 API 密鑰的 Challonge 帳戶。我們支持 HTTP 基本身份驗證。用戶名 = 您的 Challonge 用戶名,密碼 = 您的 API 密鑰。許多客戶端將這些請求格式化為: https://username:[email protected]/v1/... 或者,如果您愿意,您可以將 API 密鑰作為引數 api_key 傳遞給所有方法呼叫。
所以這應該在你的 PostCall 開始時起作用:
var userName = "your Challonge username";
var uNamePw = $"{userName}:{key}";
var encoding = Encoding.GetEncoding("ISO-8859-1");
var credentials = Convert.ToBase64String(encoding.GetBytes(uNamePw));
client.AddDefaultHeader("Authorization", $"Basic {credentials}");
或者,您應該能夠附加?api_key={your api key}到網址
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/373459.html
