Get response in JSON from API

霸气de小男生 提交于 2020-03-26 04:43:12

问题


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

}

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

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

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


回答1:


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.

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




回答2:


You should set Accept: application/json as well as Content-Type: application/json.



来源:https://stackoverflow.com/questions/30890261/get-response-in-json-from-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!