我正在尝试使用C#连接到URL。
基本上,我正在尝试做与CURL相同的事情:
curl -i -k --user ABC..:XYZ.. --data "grant_type=client_credentials" https://www.example.com/oauth/token
这是我的C#代码:
// Get the URL
string URL = "https://www.example.com/oauth/token";
//Create the http client
HttpClient client = new HttpClient();
HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Post, URL);
requestMessage.Headers.Add("contentType", "application/x-www-form-urlencoded");
requestMessage.Headers.Add("data", "grant_type=client_credentials");
requestMessage.Headers.Add("user", "ABC..:XYZ..");
//Connect to the URL
HttpResponseMessage response = client.SendAsync(requestMessage).Result;
// Get the response
string Output = response.Content.ReadAsStringAsync().Result;
卷曲代码效果很好。我得到200状态回复。但是在C#中,我得到的响应是:401,未授权。似乎没有以正确的格式提供客户端ID和密钥。
请问有人知道我的C#代码中缺少什么吗?
谢谢, 欢呼
答案 0 :(得分:3)
您的curl
命令产生POST
请求,因此要在C#中执行相同的操作,您需要一个HttpClient.PostAsync方法。
您的数据为application/x-www-form-urlencoded
,因此您可以使用FormUrlEncodedContent来简化生活。
您的最后一个问题是身份验证。为此,您应该使用AuthenticationHeaderValue。
因此,这是您的代码示例,应该可以工作:
var client = new HttpClient();
// HTTP Basic authentication
var authenticationHeaderBytes = Encoding.ASCII.GetBytes("ABC..:XYZ..");
var authenticationHeaderValue = Convert.ToBase64String(authenticationHeaderValue);
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", authenticationHeaderValue);
// POST content
var content = new FormUrlEncodedContent(
new Dictionary<string, string> { { "grant_type", "client_credentials" } });
// make request
var response = await client.PostAsync("https://www.example.com/oauth/token", content);
此外,做类似的事情还有一个普遍的错误
using (var client = new HttpClient())
{
// ...
}
坏事会发生的,不要这样做。您可以阅读更多here。长话短说-您不应在应用程序内创建(也不应允许)HttpClient
的许多实例。
答案 1 :(得分:1)
卷曲的--user
可以在c#中表示为
requestMessage.Headers["Authorization"] = "Basic " +
Convert.ToBase64String(Encoding.ASCII.GetBytes("username:password"));
赠款类型需要作为内容发送。
var content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("grant_type", "client_credentials")
});
var result = await client.PostAsync(url, content);
您还可以尝试在正文中发送用户名和密码。
using (HttpClient client = new HttpClient())
{
var req = new HttpRequestMessage(HttpMethod.Post, new Uri(url));
req.Content = new FormUrlEncodedContent(new Dictionary<string, string>
{
{ "grant_type", "client_credentials" }, // or "password"
{ "username", username },
{ "password", password }
});
var response = await client.SendAsync(req);
// No error handling for brevity
var data = await response.Content.ReadAsStringAsync();
最后,您可能需要或可能不需要设置accept标头。
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));