从API获取JSON响应 [英] Get response in JSON from API

查看:88
本文介绍了从API获取JSON响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用HttpClient来使用来自ASP.NET Web API控制器的外部API。我没有使用身份验证,只是一个令牌,所以我有:

I am using HttpClient to consume an external API from an ASP.NET Web API controller. I am not using authentication, just a token, so I have:

using (var httpClient = new HttpClient()) {

  httpClient.DefaultRequestHeaders.Accept.Clear();

  httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

  HttpResponseMessage response = await httpClient.GetAsync(endpoint);

}

我总是以XML格式获取响应,但是我发送带有 application / json的标头。

I am getting the response always in XML format but I am sending header with "application/json".

我遗漏了一些东西,这是外部API的问题吗?

Am I missing something it this is a problem with the external API?

我还能尝试用JSON获得响应吗?

What else can I try to get the response in JSON?

推荐答案

这取决于API开发人员尊重媒体类型(application / json)。开发人员有可能在客户端请求JSON(如果他们想拖钓)时显式返回XML,尽管在这种情况下,它可能只是为您提供默认格式,因为他们不检查标头值。

It's up to the API developer(s) to respect the media type (application/json). It is possible for a developer to explicitly return XML when a client requests JSON (if they feel like trolling), though in this case it is probably just giving you the default format because they don't check the header value.

检查文档或直接与他们联系以确认它们以JSON格式返回数据以及如何格式化请求以获取JSON。

Check the docs or contact them directly to confirm they return data in JSON format and how to format the request to get JSON.

这篇关于从API获取JSON响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆