繁体   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