【问题标题】:Convert curl to c# code using HttpClient使用 HttpClient 将 curl 转换为 c# 代码
【发布时间】:2015-08-29 20:37:52
【问题描述】:

我想用 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# 类的实例。

另外,当我尝试直接访问链接时,它给出了用回调()函数封装的JSON数据。

我写对了吗? 当我运行它时,它什么也没做。

谢谢。

[已修复] 所以我的问题只是没有指定标题类型。这是修复程序的代码:

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

【问题讨论】:

  • it did nothing. 无需向我们提供那么多信息。我们喜欢猜测问题.....

标签: javascript c# curl


【解决方案1】:

这就是你需要得到响应来反序列化它的方式:

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

【讨论】:

  • 对不起,我没有提到它。 RootObject 实际上是 C# 类对象的一个​​实例。我需要将从格式为 JSON 的链接中获得的信息反序列化为 rootobject。另外,我很困惑,因为当我直接从浏览器访问链接时,它给出了用 callback() 函数封装的 JSON 数据
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-07-08
  • 1970-01-01
相关资源
最近更新 更多