samedi 26 novembre 2016

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://ift.tt/hSyg9Q");
        myHttpWebRequest.Timeout = 5000;
        myHttpWebRequest.ReadWriteTimeout = 5000;
        var response = myHttpWebRequest.GetResponse();

        if (response.Equals(false))
        {
            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!




Aucun commentaire:

Enregistrer un commentaire