【问题标题】:Perform Get request in C#?在 C# 中执行获取请求?
【发布时间】:2019-11-18 03:01:38
【问题描述】:

我正在尝试使用 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;

Curl 代码效果很好。我得到一个 200 状态响应。但是在 C# 中,我得到了响应:401,未经授权。似乎没有以正确的格式提供客户端 ID 和密钥。

请问有人知道我的 C# 代码中缺少什么吗?

谢谢, 干杯

【问题讨论】:

  • 删除标题。此外,基本身份验证应该是客户端的属性
  • @theMayer 你的意思是我必须删除标题吗?如果是这样,我应该把客户端凭据放在哪里?
  • 你想搞定吗?您不能使用 get 发布数据。我认为你需要一个帖子。
  • @theMayer 当我使用 Post 时,我收到错误:401,未经授权
  • 这是因为--user ABC..:XYZ..和requestMessage.Headers.Add("user", "ABC..:XYZ..");不一样,我会发一个答案解释更多

标签: c#


【解决方案1】:

你的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 的多个实例。

【讨论】:

    【解决方案2】:

    curl的--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();
    

    最后,您可能需要也可能不需要设置接受标头。

    request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));                
    

    【讨论】:

      猜你喜欢
      • 2012-09-29
      • 2015-01-08
      • 1970-01-01
      • 1970-01-01
      • 2018-04-11
      • 2011-11-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多