Catching HttpWebRequest Timeout

霸气de小男生 提交于 2019-12-11 16:48:16

问题


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.


回答1:


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.

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




回答2:


This is an old thread, but an issue which I also hit today.

What I didn't realise is that if you have a web service which, say, attempts to write to a file which is locked... then having the code in a simple try..catch is not enough.

You must specifically have a catch which handles WebExceptions.

try
{
    //  Run your web service code
}
catch (WebException ex)
{
    //  Handle a WebException, such as trying to write to a "locked" file on the network
}
catch (Exception ex)
{
    //  Handle a regular Exception
}

I always thought that a WebException was a type of Exception, so these would get caught by this catch handler:

catch (Exception ex)
{
    //  Handle a regular Exception
}

It doesn't.

So to avoid your code throwing "Request timed out" messages, with no suggestion about what caused them, do remember to add these second catch handler.

Btw, on my web services tutorial, here's the code I recommend, which looks out for Exceptions, and returns them in the Response header:

try
{
    //  Put your code in here
}
catch (WebException ex)
{
    //  Return any exception messages back to the Response header
    OutgoingWebResponseContext response = WebOperationContext.Current.OutgoingResponse;
    response.StatusCode = System.Net.HttpStatusCode.InternalServerError;
    response.StatusDescription = ex.Message.Replace("\r\n", "");
    return null;
}
catch (Exception ex)
{
    //  Return any exception messages back to the Response header
    OutgoingWebResponseContext response = WebOperationContext.Current.OutgoingResponse;
    response.StatusCode = System.Net.HttpStatusCode.InternalServerError;
    response.StatusDescription = ex.Message.Replace("\r\n", "");
    return null;
}



回答3:


try { ... }            
catch (System.Net.WebException sne)
        {
            MessageBox.Show(req.Timeout.ToString());
        }

I think the timeout will always be "5000" no matter what. If you tell it "timeout is 5 seconds" it will always try for 5 seconds before giving up.



来源:https://stackoverflow.com/questions/14634249/catching-httpwebrequest-timeout

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!