簡體   English   中英

使用 HttpClient 將 curl 轉換為 c# 代碼

[英]Convert curl to c# code using HttpClient

我想使用 HttpClient 發送從下面的 JS 代碼中獲得的 curl 請求。

curl -v -X GET "hxxps://airport.api.aero/airport?user_key=[token]"

所以我寫了 C# 代碼

string response = await client.GetStringAsync(new Uri("hxxps://airport.api.aero/airport?user_key=[token]"));

我嘗試使用下面的代碼反序列化響應。

// deserialize the JSON object response, the information will become an AirportObject.RootObject instance
rootObject = JsonConvert.DeserializeObject<AirportObject.RootObject>(response);

rootObject 是 C# 類對象的實例,從鏈接接收的信息為 JSON 格式。 因此,它需要從 JSON 轉換為 C# 類的實例。

另外,當我嘗試直接訪問該鏈接時,它給出了用 callback() 函數封裝的 JSON 數據。

我寫的對嗎? 當我運行它時,它什么也沒做。

謝謝。

[已修復] 所以我的問題只是沒有指定標題類型。 這是修復程序的代碼:

//set request headers to accept JSON data
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

這是您需要獲得反序列化響應的方式:

HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost/api/v1/");

HttpResponseMessage response = await client.GetAsync("some");

if(response.IsSuccessfulStatusCode)
{
     // The entity is within the response's content
     RootObject root = await response.Content.ReadAsAsync<RootObject>();
}

暫無
暫無

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

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