gpt4 book ai didi

c# - 使用 HttpClient 获取 Bearer Token

转载 作者:太空狗 更新时间:2023-10-29 21:01:18 24 4
gpt4 key购买 nike

我正在尝试获取不记名 token :

public override async Task<string> Post(string path, HttpContent content) {


var encodedConsumerKey = System.Uri.EscapeDataString("1111111111111");
var encodedConsumerKeySecret = System.Uri.EscapeDataString("2222222222222");
var encodedPair = Base64Encode(String.Format("{0}:{1}", encodedConsumerKey, encodedConsumerKeySecret));

HttpRequestMessage request = new HttpRequestMessage{
Method = HttpMethod.Post,
RequestUri = new Uri("https://api.twitter.com/oauth2/token"),
Content = new StringContent("grant_type=client_credentials")
};
request.Headers.TryAddWithoutValidation("Authorization", String.Format("BASIC {0}", encodedPair));
request.Headers.TryAddWithoutValidation("Content-Type", "application/x-www-form-urlencoded");


var result = await HttpClient.SendAsync(request);
return result.Content.ReadAsStringAsync().Result;
}

private static string Base64Encode(string plainText) {
var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(plainText);
return System.Convert.ToBase64String(plainTextBytes);
}

这给我以下错误 403“禁止访问”。任何想法,将不胜感激。

最佳答案

我能够让它工作。我在上面的代码中更改了一些内容。首先是设置 ContentType

requestToken.Content.Headers.ContentType = new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded") {CharSet = "UTF-8"};

第二个是我遗漏的一个非常小的细节,降低了 Authorization header 中 Basic 字符串的大小写。

这是完整的方法,以防万一有人需要它:

public async Task<string> GetAPI(string apiPath)
{

var baseUri = new Uri("https://api.twitter.com/");
var encodedConsumerKey = HttpUtility.UrlEncode("111111111111");
var encodedConsumerKeySecret = HttpUtility.UrlEncode("222222222222");
var encodedPair = Base64Encode(String.Format("{0}:{1}", encodedConsumerKey, encodedConsumerKeySecret));

var requestToken = new HttpRequestMessage
{
Method = HttpMethod.Post,
RequestUri = new Uri(baseUri, "oauth2/token"),
Content = new StringContent("grant_type=client_credentials")
};

requestToken.Content.Headers.ContentType = new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded") { CharSet = "UTF-8" };
requestToken.Headers.TryAddWithoutValidation("Authorization", String.Format("Basic {0}", encodedPair));

var bearerResult = await HttpClient.SendAsync(requestToken);
var bearerData = await bearerResult.Content.ReadAsStringAsync();
var bearerToken = JObject.Parse(bearerData)["access_token"].ToString();

var requestData = new HttpRequestMessage
{
Method = HttpMethod.Get,
RequestUri = new Uri(baseUri, apiPath),
};
requestData.Headers.TryAddWithoutValidation("Authorization", String.Format("Bearer {0}", bearerToken));

var results = await HttpClient.SendAsync(requestData);
return await results.Content.ReadAsStringAsync();

}

关于c# - 使用 HttpClient 获取 Bearer Token,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32923325/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com