ronald677br ronald677br - 12 days ago 7
C# Question

Make HttpWebRequest.GetResponse() return a value when the connection fails

I'm developing a game on Unity that needs to reset the player lifes every 2 hours, and to avoid cheating I'm trying to use the Internet time. For that I made a simple method on C# to get the DateTime from microsoft.com. The issue is that sometimes the connection fail, and I want it to return a bool when this happens, so I can get the System.DateTime.Now and check again for the Internet time as soon a connection is available. I tried some things but nothing worked. Here is the code I'm using:

public DateTime GetInternetTime()
{
var myHttpWebRequest = (HttpWebRequest)WebRequest.Create("http://www.microsoft.com");
myHttpWebRequest.Timeout = 5000;
myHttpWebRequest.ReadWriteTimeout = 5000;
var response = myHttpWebRequest.GetResponse();

if (response == null)
{
dateTime = DateTime.Now;
connecionFailed = true;
}
string todaysDates = response.Headers["date"];
dateTime = DateTime.ParseExact(todaysDates, "ddd, dd MMM yyyy HH:mm:ss 'GMT'", CultureInfo.InvariantCulture.DateTimeFormat, DateTimeStyles.AssumeUniversal);
connecionFailed = false;
return dateTime;
}


Please help! I'm really stuck on this!

Answer

GetResponse throws an exception when an error occurs. For example if host cannot be resolved. All you need is to catch it and do proper action after it.

In code below I handle WebException, but some other exceptions can occur during this method. So you can general Exception class instead.

public DateTime GetInternetTime()
    {
        var myHttpWebRequest = (HttpWebRequest)WebRequest.Create("http://www.microsoft.com");
        myHttpWebRequest.Timeout = 5000;
        myHttpWebRequest.ReadWriteTimeout = 5000;

        try
        {
            var response = myHttpWebRequest.GetResponse();
            string todaysDates = response.Headers["date"];
            dateTime = DateTime.ParseExact(todaysDates, "ddd, dd MMM yyyy HH:mm:ss 'GMT'", CultureInfo.InvariantCulture.DateTimeFormat, DateTimeStyles.AssumeUniversal);
            connectionFailed = false;
        } catch(WebException)
        {
            connectionFailed = true;
            dateTime = DateTime.Now;
        }

        return dateTime;
    }