【发布时间】:2021-12-19 08:20:45
【问题描述】:
我在从本地 API 读取 json 时遇到问题。
这是一个众所周知的公共 json 端,我也用于测试:https://jsonplaceholder.typicode.com/todos
在 C# 中我试过这个:
HttpClient client = new HttpClient();
string httpResponse = "";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(testurl);
WebResponse responseinger = null;
StreamReader reader = null;
static async Task Main(string[] args)
{
Program p = new Program();
await p.Get();
}
public async Task Get()
{
string response = await client.GetStringAsync("https://jsonplaceholder.typicode.com/todos");
Console.WriteLine(response);
Console.WriteLine();
string response2 = await client.GetStringAsync(testurl);
Console.WriteLine(response2);
Console.WriteLine();
string json = JsonConvert.SerializeObject(response2);
Console.WriteLine(json);
Console.WriteLine();
try
{
responseinger = request.GetResponse();
}
catch (WebException ex)
{
responseinger = ex.Response;
}
reader = new StreamReader(responseinger.GetResponseStream());
httpResponse = reader.ReadToEnd();
Console.WriteLine(reader);
Console.WriteLine();
Console.WriteLine(httpResponse);
Console.WriteLine();
using (WebClient wc = new WebClient())
{
var jsonwc = wc.DownloadString(testurl);
Console.WriteLine(jsonwc);
Console.WriteLine();
}
}
所以我使用了不同的方法来获取我的 json。
来自公共 json 端的 json 有效,但我的本地没有。
我能做些什么呢?提前致谢!
【问题讨论】:
-
我怀疑您的 API 正在压缩响应,可能没有请求请求。您应该查看请求和响应中的标头以检查(尤其是 Accept-Encoding)。真的很难说更多。
-
如果我查看 Postman。在 Content-encoding 的 API URL 标头上,它说 gzip 可能是问题所在?
-
也许——如果 Postman 发送一个 Accept-encoding 标头说它支持 gzip,那也没关系。但是您对 Postman 请求/响应不感兴趣 - 您对 C# 请求/响应感兴趣。因此,请查看响应标头,最好是请求标头。如有必要,使用 Fiddler 和/或 Wireshark 检查电线上的实际内容。如果 API 在客户端未声明支持时返回 gzip 编码的数据,则说明 API 存在问题。
-
好的,我解决了。感谢您的编码提示。它引导我朝着正确的方向前进。更新了我的问题。
-
谢谢