我想知道你是否可以帮我解决我遇到的一个错误。我有一个我创建的HTTP管理器,可以帮助我处理来自网站的POSTing / GETing数据。直到最近,当我尝试使用两者的混合物时,它一直工作正常。第一个循环循环一切正常,在第二个循环上它挂起在HttpWebRequest.GetRequestStream()上。我已经在网上阅读并找不到真正的解决方案。以下是提取/接收的代码块:
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] buffer = encoding.GetBytes(_PostData);
_HttpWebRequest = (HttpWebRequest)WebRequest.Create(_FetchUrl);
_HttpWebRequest.Credentials = _Credentials;
_HttpWebRequest.Method = _RequestType.ToString();
_HttpWebRequest.ContentType = "application/x-www-form-urlencoded";
_HttpWebRequest.ContentLength = buffer.Length;
_HttpWebRequest.UserAgent = userAgent;
_HttpWebRequest.CookieContainer = _CookieContainer;
_HttpWebRequest.KeepAlive = false;
_HttpWebRequest.AllowAutoRedirect = _AllowAutoRedirect;
_HttpWebRequest.AutomaticDecompression = DecompressionMethods.GZip;
_HttpWebRequest.ServicePoint.Expect100Continue = false;
if (_RequestType.Equals(RequestTypes.POST))
{
// Write POST
Stream reqStream = _HttpWebRequest.GetRequestStream();
{
reqStream.Write(buffer, 0, buffer.Length);
reqStream.Flush();
reqStream.Close();
}
}
响应:
HttpWebResponse httpWebResponse = (HttpWebResponse)_HttpWebRequest.GetResponse();
{
Stream responseStream = httpWebResponse.GetResponseStream();
{
if (_UseGzip)
{
if (httpWebResponse.ContentEncoding.ToLower().Contains("gzip"))
{
responseStream = new GZipStream(responseStream, CompressionMode.Decompress);
}
else
{
responseStream = new DeflateStream(responseStream, CompressionMode.Decompress);
}
}
if (responseStream != null)
{
StreamReader streamReader = new StreamReader(responseStream);
{
try
{
_PageContent = streamReader.ReadToEnd();
}
finally
{
streamReader.Close();
responseStream.Close();
httpWebResponse.Close();
}
}
}
else
{
_PageContent = string.Empty;
}
}
}
_HttpWebRequest.Abort();
任何人都可以看到我的代码挂起的原因有什么缺陷吗?所有流都被关闭了,我已经将允许的连接设置为超过100,我不明白为什么这会破坏。
答案 0 :(得分:11)
这可能是因为您没有丢弃您的WebResponse或流或StreamReader:
var request = WebRequest.Create(...);
using (var response = request.GetResponse())
{
using (var responseStream = response.GetResponseStream())
{
using (var reader = new StreamReader(responseStream))
{
// use the reader
}
}
}
答案 1 :(得分:2)
我遇到了同样的问题。我使用这些块正确地关闭(处置)了所有流和HttpWebResponse。当我发送由ThreadAbortExceptions中止的请求时,问题仍然存在。最后,当ThreadAbortException发生时,它有助于调用myWebRequest.Abort()!希望这会有所帮助。
答案 2 :(得分:0)
我看到你使用:
HttpWebRequest.AutomaticDecompression = DecompressionMethods.GZip;
随着手动减压方法:
if (httpWebResponse.ContentEncoding.ToLower().Contains("gzip"))
{
responseStream = new GZipStream(responseStream, CompressionMode.Decompress);
}
else
{
responseStream = new DeflateStream(responseStream, CompressionMode.Decompress);
}
没有尝试它是否真的重要,但我只使用手动方法和类似的代码,它工作正常。实际上我有悬挂问题,但只有一个域,试验属性显示差异。
哦,我怀疑如果你不使用任何后期数据压缩,你需要删除内容编码标题