我为一个程序创建了一个函数,当请求类型为时它确实有效GET
,如果是POST
,它总是在行上产生超时异常(并且没有达到 50s 的超时)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) };
}
}