request.timeout doesn't throw exception - c#

Uri URL2 = new Uri(#"http://www......com");
HttpWebRequest request2 = (HttpWebRequest)WebRequest.Create(URL2);
request2.Timeout = 10000;
HttpWebResponse response2 = (HttpWebResponse)request2.GetResponse();
I am making webrequest with the codes above. When I write a stupid url such as www.oiasjdilasod.com it throws exception; however when an existing page is not available for few hours I cannot get this exception. it doesn't throw any exception and stop running.
When this page is not available i tried at internet explorer, it showed page can not be found http 400 bad request.
Do you have any suggestions how to catch this exception?

The fact that you are getting a response back from the server means that it's available, it's just not working properly - therefore the request is made and doesn't time out because the server has responded.
It's just not the response you wanted.
Instead, you should check the StatusCode property.
if(response2.StatusCode != HttpStatusCode.OK)
{
throw new Exception("Site is responding incorrectly!");
}

i had the same problem before and
catch(WebException e)
{
Console.WriteLine(e.toString());
}
will solve it

This Piece of Code Worked for me
try
{
Uri URL2 = new Uri(#"http://www.*****.com");
HttpWebRequest request2 = (HttpWebRequest)WebRequest.Create(URL2);
request2.Timeout = 100;
HttpWebResponse response2 = (HttpWebResponse)request2.GetResponse();
}
catch (WebException e)
{
MessageBox.Show(e.Message.ToString());
}

What exception are you throwing? A regular Exception won't do, it has to be a WebException.
...
catch(WebException e)
{
Console.WriteLine("Error: "+ e.Status);
}
EDIT:
How about a Timeout Exception (Along with the WebException)?
catch (TimeoutException e)
{
Console.WriteLine(e);
}
catch(WebException e)
{
Console.WriteLine("Error: "+ e.Status);
}

Related

C# Exceptions Not Being Handled

The following code is called via the browser and if an exception occurs that exception is never caught by the 'Try Catch' but instead the exception is reported to the screen. I have tried running without debug as well as turning off CLR errors. Any suggestions would be appreciated:
public string GetUrl(string url)
/*Grab remote page */
{
string target = string.Empty;
HttpWebRequest httpWebRequest = null;
HttpWebResponse response = null;
StreamReader streamReader = null;
try
{
httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
response = (HttpWebResponse)httpWebRequest.GetResponse();
streamReader = new StreamReader(response.GetResponseStream(), true);
target = streamReader.ReadToEnd();
}
catch (WebException e)
{
Console.WriteLine("Error:GetUrl()");
Console.WriteLine("\n{0}", e.Message);
Console.WriteLine("\n{0}", e.Status);
}
finally
{
streamReader.Close();
response.Close();
}
return target;
}
You are only catching webexceptions, any other exception is not caught.
It can throw more exceptions see here :
https://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.getresponse%28v=vs.110%29.aspx
Add one more catch block before finally block and trap base Excaption. It will catch all type of error occurred and not caught in earlier catch blocks.

HttpWebRequest timeout handling

I have a really simple question. I am uploading files to a server using HTTP POST. The thing is I need to specially handle connection timeouts and add a bit of a waiting algorithm after a timeout has occurred to relive the server.
My code is pretty simple:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("SomeURI");
request.Method = "POST";
request.ContentType = "application/octet-stream";
request.KeepAlive = true;
request.Accept = "*/*";
request.Timeout = 300000;
request.AllowWriteStreamBuffering = false;
try
{
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
WebHeaderCollection headers = response.Headers;
using (Stream Answer = response.GetResponseStream())
{
// Handle.
}
}
}
catch (WebException e)
{
if (Timeout_exception)
{
//Handle timeout exception
}
}
I omitted the file reading code as it is not our concern. Now I need to make sure that once a WebException is thrown, I filter the exception to see if it is indeed a timeout exception. I thought of comparing against the exception message yet I am not sure if this is the right way since the application in question is a commercial app and I am afraid that the message varies between different languages. And what message should I be looking for.
Any suggestions?
You can look at WebException.Status. The WebExceptionStatus enum has a Timeout flag:
try
{
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
WebHeaderCollection headers = response.Headers;
using (Stream answer = response.GetResponseStream())
{
// Do stuff
}
}
}
catch (WebException e)
{
if (e.Status == WebExceptionStatus.Timeout)
{
// Handle timeout exception
}
else throw;
}
Using C# 6 exception filters can come in handy here:
try
{
var request = WebRequest.Create("http://www.google.com");
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
WebHeaderCollection headers = response.Headers;
using (Stream answer = response.GetResponseStream())
{
// Do stuff
}
}
}
catch (WebException e) when (e.Status == WebExceptionStatus.Timeout)
{
// If we got here, it was a timeout exception.
}
Yuval's answer is quite a direct hit but here's a version of mine which I've tried since I've undergone in the same circumstance if you want to target via Status codes:
catch (WebException ex)
{
var hwr = (HttpWebResponse)ex.Response;
if (hwr != null)
{
var responseex = hwr.StatusCode;
int statcode = (int)responseex;
if (statcode == 404)
{
Utility.Instance.log(logPath, "The file might not be availble yet at the moment. Please try again later or contact your system administrator.", true);
}
if (statcode == 401)
{
Utility.Instance.log(logPath, "Username and Password do not match.", true);
}
if (statcode == 408)
{
Utility.Instance.log(logPath, "The operation has timed out", true);
}
}
else
{
Utility.Instance.log(logPath, ex + ". Please contact your administrator.", true);//Or you can do a different thing here
}
}

Uri.IsWellFormedUriString returns true, but cannot read from a url

I am trying to check if the url http://master.dev.brandgear.net is valid by the following method:
private bool UrlIsValid(string url)
{
using (var webClient = new WebClient())
{
bool response;
try
{
webClient.UseDefaultCredentials = true;
using (Stream strm = webClient.OpenRead(url))
{
response = true;
}
}
catch (WebException we)
{
response = false;
}
return response;
}
}
However, I am getting a web exception "404 not found.". I have checked the uri with Uri.IsWellFormedUriString and it is returning true. However, the same url can be opened through a browser. Any idea how to validate it?
I ran your example with following URL http://master.dev.brandgear.net and exception is also raised. If you open same URL in browser (for example Firefox) and run Firebug plugin, open Network tab you will see error 404 (Page not found). Your code is OK, but server returns 404.
To really get a response, you have to use WebException instead of GetResponse or GetResponseStream methods when the 404 exception happens.Also use HttpWebRequest and HttpWebResponse in these situations for better control,so after the exception occurs you check its state to see if its a ProtocolError and if so get the response from there:
private bool UrlIsValid(string url)
{
bool response = false;
HttpWebResponse rep = null;
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
rep = (HttpWebResponse)request.GetResponse();
}
catch (WebException we)
{
if (we.Status == WebExceptionStatus.ProtocolError)
rep = (HttpWebResponse)we.Response;
}
if (rep != null)
{
try
{
using (Stream strm = rep.GetResponseStream())
{
response = true;
}
}
catch (WebException ex)
{
//no need variable is already false if we didnt succeed.
//response = false;
}
}
return response;
}

Catching HttpWebRequest Timeout

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.
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.
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;
}
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.

Exception handling the right way for WebClient.DownloadString

I was wondering what exceptions I should protect myself against when using WebClient.DownloadString.
Here's how I'm currently using it, but I'm sure you guys can suggest better more robust exception handling.
For example, off the top of my head:
No internet connection.
Server returned a 404.
Server timed out.
What is the preferred way to handle these cases and throw the exception to the UI?
public IEnumerable<Game> FindUpcomingGamesByPlatform(string platform)
{
string html;
using (WebClient client = new WebClient())
{
try
{
html = client.DownloadString(GetPlatformUrl(platform));
}
catch (WebException e)
{
//How do I capture this from the UI to show the error in a message box?
throw e;
}
}
string relevantHtml = "<tr>" + GetHtmlFromThisYear(html);
string[] separator = new string[] { "<tr>" };
string[] individualGamesHtml = relevantHtml.Split(separator, StringSplitOptions.None);
return ParseGames(individualGamesHtml);
}
If you catch WebException, it should handle most cases. WebClient and HttpWebRequest throw a WebException for all HTTP protocol errors (4xx and 5xx), and also for network level errors (disconnection, host not reachable, etc)
How do I capture this from the UI to show the error in a message box?
I'm not sure I understand your question... Can't you just show the exception message?
MessageBox.Show(e.Message);
Don't catch the exception in FindUpcomingGamesByPlatform, let it bubble up to the calling method, catch it there and show the message...
I usually handle it like this to print any exception message the remote server is returning. Given that the users are allowed to see that value.
try
{
getResult = client.DownloadString(address);
}
catch (WebException ex)
{
String responseFromServer = ex.Message.ToString() + " ";
if (ex.Response != null)
{
using (WebResponse response = ex.Response)
{
Stream dataRs = response.GetResponseStream();
using (StreamReader reader = new StreamReader(dataRs))
{
responseFromServer += reader.ReadToEnd();
}
}
}
_log.Error("Server Response: " + responseFromServer);
MessageBox.Show(responseFromServer);
}
I use this code:
Here I init the webclient whithin the loaded event
private void LayoutRoot_Loaded(object sender, RoutedEventArgs e)
{
// download from web async
var client = new WebClient();
client.DownloadStringCompleted += client_DownloadStringCompleted;
client.DownloadStringAsync(new Uri("http://whateveraurisingis.com"));
}
The callback
void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
#region handle download error
string download = null;
try
{
download = e.Result;
}
catch (Exception ex)
{
MessageBox.Show(AppMessages.CONNECTION_ERROR_TEXT, AppMessages.CONNECTION_ERROR, MessageBoxButton.OK);
}
// check if download was successful
if (download == null)
{
return;
}
#endregion
// in my example I parse a xml-documend downloaded above
// parse downloaded xml-document
var dataDoc = XDocument.Load(new StringReader(download));
//... your code
}
Thanks.
According to the MSDN documentation, the only non-programmer exception is WebException, which can be raised if:
The URI formed by combining BaseAddress and address is invalid.
-or-
An error occurred while downloading the resource.

Categories

Resources