我为程序做出了一个函数,当请求类型为 GET
时确实有效,如果它是 POST
,它总是会产生超时异常(并且未达到50秒的超时)线HttpWebResponse response = (HttpWebResponse)request.GetResponse();
我尝试了很多事情,但是我没有发现原因,可能有人知道。
编辑:如果某人有兴趣,请工作:https://gist.github.com/4347248
任何帮助将不胜感激。
我的代码是:
public ResRequest request(string URL, RequestType typ, CookieCollection cookies, string postdata ="", int timeout= 50000)
{
byte[] data;
Stream req;
Stream resp;
HttpWebRequest request = WebRequest.Create(URL) as HttpWebRequest;
request.Timeout = timeout;
request.ContinueTimeout = timeout;
request.ReadWriteTimeout = timeout;
request.Proxy = new WebProxy("127.0.0.1", 8118);
request.Headers.Add(HttpRequestHeader.AcceptLanguage, "de");
request.Headers.Add("UA-CPU", "x86");
request.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip, deflate");
request.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; WOW64; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; .NET CLR 3.5.21022; .NET CLR 3.5.30729; .NET CLR 3.0.30618) ";
request.CookieContainer = new CookieContainer();
request.CookieContainer.Add(cookies);
if (typ == RequestType.POST)
{
data = System.Text.Encoding.Default.GetBytes(postdata);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
req = request.GetRequestStream();//after a few tries this produced a Timeout error
req.Write(data, 0, data.Length);
req.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();//This line produces a Timeout Exception
resp = response.GetResponseStream();
if ((response.ContentEncoding.ToLower().Contains("gzip")))
{
resp = new System.IO.Compression.GZipStream(resp, System.IO.Compression.CompressionMode.Decompress);
} else if ((response.ContentEncoding.ToLower().Contains("deflate"))) {
resp = new System.IO.Compression.DeflateStream(resp, System.IO.Compression.CompressionMode.Decompress);
}
return new ResRequest() { result = new System.IO.StreamReader(resp, System.Text.Encoding.UTF8).ReadToEnd(), cookies = response.Cookies, cstring = cookiestring(response.Cookies) };
}
else
{
request.Method = "GET";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
resp = response.GetResponseStream();
if ((response.ContentEncoding.ToLower().Contains("gzip")))
{
resp = new System.IO.Compression.GZipStream(resp, System.IO.Compression.CompressionMode.Decompress);
}
else if ((response.ContentEncoding.ToLower().Contains("deflate")))
{
resp = new System.IO.Compression.DeflateStream(resp, System.IO.Compression.CompressionMode.Decompress);
}
return new ResRequest() { result = new System.IO.StreamReader(resp, System.Text.Encoding.UTF8).ReadToEnd(), cookies = response.Cookies, cstring = cookiestring(response.Cookies) };
}
}
所以它每次都挂在 req.GetRequestStream()
上,还是起作用"几次尝试"然后挂起?
如果它工作几次然后悬挂,则可能无法正确关闭请求,这会导致您无法连接。确保Close()
和/或Dispose()
HttpWebResponse
对象以及您要创建的所有流和读取器。
您必须使用响应。dispose();
方法的结尾