使用 HttpClient 获取 Bearer Token
Obtain Bearer Token using HttpClient
我正在尝试获取不记名令牌:
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 'Forbidden'。任何想法,将不胜感激。
我能够让它工作。我在上面的代码中更改了一些内容。首先是设置 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();
}
我正在尝试获取不记名令牌:
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 'Forbidden'。任何想法,将不胜感激。
我能够让它工作。我在上面的代码中更改了一些内容。首先是设置 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();
}