gpt4 book ai didi

c# - 有谁知道为什么我会收到 HttpWebRequest 超时?

转载 作者:可可西里 更新时间:2023-11-01 09:05:53 26 4
gpt4 key购买 nike

我想知道您是否可以帮助我解决我遇到的一个错误。我有一个我创建的 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 多个,我不明白为什么会中断。

最佳答案

这可能是因为您没有处理 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
}
}
}

关于c# - 有谁知道为什么我会收到 HttpWebRequest 超时?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2242866/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com