
[英]GET request works in browser and Postman, but I get Unauthorized when using HttpClient and RestSharp
[英]Restsharp GET Call Works, but POST is Unauthorized?
我正在为 challonge.com 开发一个 RestSharp API 调用程序,我遇到了授权问题。 进行 GET 调用时,一切正常,我可以获得所需的信息。 但是,在尝试 POST 调用时,状态代码返回为未经授权,尽管使用了相同的 API 密钥。 我尝试在请求正文中包含密钥并作为参数,但似乎都不起作用。
以下是我正在拨打的电话:
-获取: 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();
}
}
验证
与 API 的所有交互都需要具有经过验证的 email 地址和 API 密钥的 Challonge 帐户。 我们支持 HTTP 基本认证。 用户名 = 您的 Challonge 用户名,密码 = 您的 API 密钥。 许多客户端将这些请求格式化为: https://username:api-key@api.challonge.com/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}");
或者,您应该能够 append ?api_key={your api key}
到 url
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.