我必须在 HttpWebRequest
对象中添加内容编码并接受为标头(带有GZIP压缩)。设置接受编码是通过添加以下行完成的:request.AutomaticDecompression = DecompressionMethods.GZip;
,这还可以。但是,在设置内容编码(我不确定是否正确完成)之后,使用此行request.Headers.Add(HttpRequestHeader.ContentEncoding, "gzip");
,我会收到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);
}
我建议检查您的请求URI。仅当您的请求URI错误时,您才能获得404。服务器上不存在资源,或者您的服务器不存在。
如果您在类似编码之类的标题中的其他位置给出了错误的值,则意味着Origin服务器不支持编码,您会获得不同的错误代码。.此处是415(未支撑),但没有404。
错误的标头字段被设置为" gzip"。
ContentEncoding
在完成任何gzzipping等之前,与数据中的字符类型有关。它具有表示编码的值,例如" ascii"," utf7"," utf32"等。
" GZIP"是通过HttpRequestHeader.ContentType
指定的MIME类型。请参阅此处。