簡體   English   中英

在 C# 中執行 Get 請求?

[英]Perform Get request in C#?

我正在嘗試使用 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# 代碼中缺少什么嗎?

謝謝,加油

您的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())
{
    // ...
}

不好的事情會發生,不要這樣做。 你可以 在這里閱讀更多。 長話短說 - 你不應該在你的應用程序中創建(也不應該允許)許多HttpClient實例。

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

最后,您可能需要也可能不需要設置接受 header。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM