我必須將Content-Encoding和Accept-Encoding作爲標頭(使用gzip壓縮)添加到HttpWebRequest
對象。設置接受編碼是通過添加以下行來完成的:request.AutomaticDecompression = DecompressionMethods.GZip;
並且沒問題。但是,使用此行request.Headers.Add(HttpRequestHeader.ContentEncoding, "gzip");
設置Content-Encoding(我不確定它是否正確完成)之後,我收到404錯誤。這裏是我的請求代碼:將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);
}
感謝您的回答。但是,如果我的請求uri錯了,我不會得到404錯誤,沒有該行'request.Headers.Add(HttpRequestHeader.ContentEncoding,「gzip」);' –