// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
namespace Microsoft.Graph
{
using System.IO.Compression;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading;
using System.Threading.Tasks;
///
/// A implementation that handles compression.
///
public class CompressionHandler : DelegatingHandler
{
///
/// Constructs a new .
///
public CompressionHandler()
{
}
///
/// Constructs a new .
///
/// An HTTP message handler to pass to the for sending requests.
public CompressionHandler(HttpMessageHandler innerHandler)
: this()
{
InnerHandler = innerHandler;
}
///
/// Sends a HTTP request.
///
/// The to be sent.
/// The for the request.
///
protected override async Task SendAsync(HttpRequestMessage httpRequest, CancellationToken cancellationToken)
{
StringWithQualityHeaderValue gzipQHeaderValue = new StringWithQualityHeaderValue(CoreConstants.Encoding.GZip);
// Add Accept-encoding: gzip header to incoming request if it doesn't have one.
if (!httpRequest.Headers.AcceptEncoding.Contains(gzipQHeaderValue))
{
httpRequest.Headers.AcceptEncoding.Add(gzipQHeaderValue);
}
HttpResponseMessage response = await base.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Decompress response content when Content-Encoding: gzip header is present.
if (ShouldDecompressContent(response))
{
response.Content = new StreamContent(new GZipStream(await response.Content.ReadAsStreamAsync(), CompressionMode.Decompress));
}
return response;
}
///
/// Checks if a contains a Content-Encoding: gzip header.
///
/// The to check for header.
///
private bool ShouldDecompressContent(HttpResponseMessage httpResponse)
{
return httpResponse.Content != null && httpResponse.Content.Headers.ContentEncoding.Contains(CoreConstants.Encoding.GZip);
}
}
}