Compress a HttpWebRequest using gzip

后端 未结 2 1011
面向向阳花
面向向阳花 2021-01-24 02:15

I am developing a .NET 4.0 Console Application to serve as a SOAP Web Service client which will send data (POST) through to a third-party. I have no c

相关标签:
2条回答
  • 2021-01-24 03:12

    I think I was able to solve the compression error message by adding the following to the HttpWebRequest method:

    request.Headers.Add(HttpRequestHeader.ContentEncoding, "gzip"); 
    

    Updated Method to create the HttpWebRequest:

    private static HttpWebRequest CreateWebRequest(SoapAction action)
    {
        string url = GetUrlAddress(action);
    
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
    
        request.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip, deflate");
        request.Headers.Add(HttpRequestHeader.ContentEncoding, "gzip"); 
        request.Headers.Add("SOAPAction", action.ToString());
        request.ContentType = "application/xop+xml";
        request.Accept = "text/xml";
        request.Method = "POST";
    
        request.ClientCertificates.Add(/* Retrieve X509Certificate Object*/);
    
        return request;
    }
    
    0 讨论(0)
  • 2021-01-24 03:15

    Use the following in place of your current code to send the request.

    using (Stream stream = request.GetRequestStream())
    using (GZipStream gz = new GZipStream(stream, CompressionMode.Compress, false))
    {
        soapXml.Save(gz);
    }
    

    Edit: Might need to use "new GZipStream(stream, CompressionMode.Compress, true)". Can't say for certain how that constructor parameter will affect the web request stream.

    0 讨论(0)
提交回复
热议问题