捕获HttpWebRequest超时 [英] Catching HttpWebRequest Timeout

查看:183
本文介绍了捕获HttpWebRequest超时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public int loginEmail(string email, string password)
    {
        HttpWebRequest request = null;
        string responseStr = null;
        string Email = email;
        string Pass = password;

        UTF8Encoding encoding = new UTF8Encoding();
        string postData = "PostData";
        byte[] data = encoding.GetBytes(postData);

        request = (HttpWebRequest)WebRequest.Create("url");
        request.Method = "POST";
        request.ContentType = "application/x-www-form-urlencoded";
        request.AllowAutoRedirect = false;
        request.KeepAlive = false;
        request.Proxy = null;
        request.ServicePoint.ConnectionLimit = 1000;
        request.ContentLength = data.Length;
        request.Timeout = 5000;
        request.ServicePoint.ConnectionLeaseTimeout = 5000;
        request.ServicePoint.MaxIdleTime = 5000;

        using (Stream stream = request.GetRequestStream())
        {
            stream.Write(data, 0, data.Length);
        }

        try
        {
            using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
            {
                responseStr = response.Headers["Set-Cookie"];
            }
        }
        catch
        {
            return 1;
        }

        string[] cooktemp;
        string[] seperatortemp = new string[] { ";" };
        cooktemp = responseStr.Split(seperatortemp, StringSplitOptions.None);

        LoginHeaders[0] = cooktemp[0] + ";";

        return 0;
    }

这段代码运行得很好,但是有时请求没有得到响应.当请求没有得到响应时,程序将挂起,然后最终将给出超时错误,使程序崩溃.我现在想做的只是捕获超时错误,以便我可以处理它,但似乎什么也没发现.

This code runs just fine, but sometimes the request does not get a response back. When the request doesn't get a response back the program will hang and then finally it will give a timeout error that crashes the program. All I am trying to do right now is just catch the timeout error so I can handle it, but nothing seems to be catching it.

推荐答案

最有可能在GetRequestStream()中超时. 文档特别指出,如果在以下情况下可能会抛出WebException:请求的过期时间已过期.

It is most likely timing out in GetRequestStream(). The documentation specifically states that it may throw WebException if the time-out period for the request expired.

因此,在您的try/catch中包含该代码块,您应该可以捕获它.

So include that block of code inside your try/catch and you should be able to catch it.

这篇关于捕获HttpWebRequest超时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆