我正在尝试连接到从 WCF 服务(WCF 服务到 WCF 服务)返回 GZip 编码 JSON 的 api。我正在使用 HTTPClient 连接到 API,并且能够将 JSON 对象作为字符串返回。但是我需要能够将返回的数据存储在数据库中,因此我认为最好的方法是将 JSON 对象返回并存储在数组或字节或类似的东西中。
我遇到的具体问题是 GZip 编码的解压缩,并且一直在尝试许多不同的示例,但仍然无法获得它。
以下代码是我如何建立连接并获得响应,这是从 API 返回字符串的代码。
public string getData(string foo)
{
string url = "";
HttpClient client = new HttpClient();
HttpResponseMessage response;
string responseJsonContent;
try
{
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
response = client.GetAsync(url + foo).Result;
responseJsonContent = response.Content.ReadAsStringAsync().Result;
return responseJsonContent;
}
catch (Exception ex)
{
System.Windows.Forms.MessageBox.Show(ex.Message);
return "";
}
}
我一直在关注一些不同的例子,比如 StackExchange API , MSDN ,还有几个在stackoverflow上,但我无法让其中任何一个为我工作。
实现这一目标的最佳方法是什么,我是否走在正确的轨道上?
谢谢大家。
最佳答案
只需像这样实例化 HttpClient:
HttpClientHandler handler = new HttpClientHandler()
{
AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate
};
using (var client = new HttpClient(handler)) //see update below
{
// your code
}
2020 年 6 月 19 日更新: 不建议在 'using' block 中使用 httpclient,因为它可能会导致端口耗尽。
private static HttpClient client = null;
ContructorMethod()
{
if(client == null)
{
HttpClientHandler handler = new HttpClientHandler()
{
AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate
};
client = new HttpClient(handler);
}
// your code
}
如果使用 .Net Core 2.1+,请考虑使用 IHttpClientFactory并像这样在你的启动代码中注入(inject)。
var timeout = Policy.TimeoutAsync<HttpResponseMessage>(
TimeSpan.FromSeconds(60));
services.AddHttpClient<XApiClient>().ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler
{
AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate
}).AddPolicyHandler(request => timeout);
https://stackoverflow.com/questions/20990601/