我为一个程序创建了一个函数,当请求类型为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) };
}
}
答案 0 :(得分:16)
它每次都挂在req.GetRequestStream()
上,还是“几次尝试”然后挂起?
如果它运行了几次然后挂起,则可能是您没有正确关闭请求,这会导致连接用完。确保Close()
和/或Dispose()
HttpWebResponse
个对象以及您正在创建的所有Streams和Readers。
答案 1 :(得分:1)
你必须使用 response.Dispose();
方法结束