将Content-Encoding添加为请求标头后出现404错误

时间:2016-12-08 14:19:37

标签: c# .net visual-studio httpwebrequest content-encoding

我必须将Content-Encoding和Accept-Encoding作为标头(使用gzip压缩)添加到HttpWebRequest对象。设置Accept-Encoding是通过添加以下行来完成的:request.AutomaticDecompression = DecompressionMethods.GZip;并且没问题。但是,在使用此行request.Headers.Add(HttpRequestHeader.ContentEncoding, "gzip");设置Content-Encoding(我不确定它是否正确完成)后,我收到404错误。这是我的请求代码:

XmlDocument RequestAndResponseHelper(string requestStr, string directory)
{
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(directory);

    var data = Encoding.ASCII.GetBytes(requestStr);
    request.Method = "POST";
    request.ContentLength = data.Length;
    request.ContentType = "text/xml";

    request.Headers.Add("userName", UserName);  
    request.Headers.Add("password", Password); 

    request.AutomaticDecompression = DecompressionMethods.GZip; //this adds  'Accept-Encoding: gzip' as request header
    request.Headers.Add(HttpRequestHeader.ContentEncoding, "gzip"); //this adds 'Content-Encoding: gzip' as request header

    using (var stream = request.GetRequestStream())
    {
        stream.Write(data, 0, data.Length);
    }

    var response = (HttpWebResponse)request.GetResponse();
    string responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();

    XmlDocument rs = new XmlDocument();
    rs.LoadXml(responseString);

    return rs;
}

如果你能帮助我处理这个错误,我真的很感激。

此外,这是我的压缩代码,也许有压缩的东西。

String Compress(String requestStr)
{
    byte[] buffer = Encoding.UTF8.GetBytes(requestStr);
    MemoryStream ms = new MemoryStream();
    using (GZipStream zip = new GZipStream(ms, CompressionMode.Compress, true))
    { zip.Write(buffer, 0, buffer.Length); }
    ms.Position = 0;
    MemoryStream outStream = new MemoryStream();
    byte[] compressed = new byte[ms.Length];
    ms.Read(compressed, 0, compressed.Length);
    byte[] gzBuffer = new byte[compressed.Length + 4];
    System.Buffer.BlockCopy(compressed, 0, gzBuffer, 4, compressed.Length);
    System.Buffer.BlockCopy(BitConverter.GetBytes(buffer.Length), 0, gzBuffer, 0, 4);
    return Convert.ToBase64String(gzBuffer);
}

2 个答案:

答案 0 :(得分:1)

我建议检查你的请求uri。只有在您的请求uri错误时才会获得404。服务器上不存在资源,或者服务器已关闭。

如果您在ContentEncoding等标题中的其他位置给出了错误的值,则意味着原始服务器不支持编码,您会得到不同的错误代码......其中415(不支持)但不是404。

答案 1 :(得分:0)

错误的标题字段被设置为“gzip”。

在完成任何gzipping等之前,

ContentEncoding与数据中的字符类型有关。它具有表示编码的值,例如“Ascii”,“UTF7”,“UTF32”等。请参阅herehere

“Gzip”是通过HttpRequestHeader.ContentType指定的MIME类型。请参阅here