HttpClient returns html 来自 API
HttpClient returns html from API
正在尝试使用 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;
}
}
作为旁注,您可能需要考虑将 HttpClient
声明为静态的。 its documentation. Also if you want json, you need to use DeserializeObject
方法推荐:
var result = JsonConvert.DeserializeObject<RootObject>(responseString);
您只需要确保您已经从 Nuget 包中安装了 Newtonsoft.Json
,并将以下内容添加到您的 using
指令中:
using Newtonsoft.Json;
我认为 API 正在寻找用户代理。
尝试添加
client.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36")
正在尝试使用 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;
}
}
作为旁注,您可能需要考虑将 HttpClient
声明为静态的。 its documentation. Also if you want json, you need to use DeserializeObject
方法推荐:
var result = JsonConvert.DeserializeObject<RootObject>(responseString);
您只需要确保您已经从 Nuget 包中安装了 Newtonsoft.Json
,并将以下内容添加到您的 using
指令中:
using Newtonsoft.Json;
我认为 API 正在寻找用户代理。
尝试添加
client.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36")