【发布时间】:2020-02-05 07:37:33
【问题描述】:
尝试使用 HttpClient 从 API 获取 json 响应,但不断获取 html 响应。在浏览器和 Postman 中,我只需输入 url 即可得到 json 格式的结果。使用 RestSharp 时,我也会得到 json 格式的响应。我需要添加什么才能获得 json 中的响应? html 字符串中的变量 responseString,而不是 json 字符串。
我使用 .net core 3.1。
代码如下:
class Program
{
static async Task Main(string[] args)
{
var response = await GetResponse();
System.Console.ReadKey();
}
public static async Task<string> GetResponse()
{
var client = new HttpClient();
client.BaseAddress = new Uri("https://musicbrainz.org/ws/2/");
client.DefaultRequestHeaders.Add("Accept",
"application/json");
using var response = await client.GetAsync((
"/artist/5b11f4ce-a62d-471e-81fc-a69a8278c7da?fmt=json&inc=url-rels+release-groups"));
response.EnsureSuccessStatusCode();
var responseString = await response.Content.ReadAsStringAsync();
return responseString;
}
}
【问题讨论】:
-
检查
responseString在某些在线 json 解析器中是一个有效的 json 字符串。如果是,你没有得到 html。您需要将其反序列化为具体对象 -
编辑问题澄清了响应是在html中,而不是在json中。
-
你能分享一下 HTML 响应吗?
-
你能用
WebClient类代替吗?
标签: c# .net .net-core dotnet-httpclient