HTTPClient レスポンスからの GZip ストリームの解凍 質問する

HTTPClient レスポンスからの GZip ストリームの解凍 質問する

私はWCFサービス(WCFサービスからWCFサービス)からGZipエンコードされたJSONを返すAPIに接続しようとしています。私はHTTPクライアント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 "";
    }
}

私はこのようないくつかの異なる例に従ってきましたスタックエクスチェンジAPIマイクロソフト、stackoverflow にもいくつかありますが、どれもうまく動作しませんでした。

これを達成するための最善の方法は何ですか、私は正しい方向に進んでいるのでしょうか?

みんなありがとう。

ベストアンサー1

次のように 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' ブロックで 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以降を使用している場合は、IHttpクライアントファクトリー起動コードに次のように挿入します。

 var timeout = Policy.TimeoutAsync<HttpResponseMessage>(
            TimeSpan.FromSeconds(60));

 services.AddHttpClient<XApiClient>().ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler
        {
            AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate
        }).AddPolicyHandler(request => timeout);

おすすめ記事