dimanche 2 juillet 2017

Fetch HTTP status code in C#

I apologise if this is an obvious, stupid or previously answered question... but I've been searching around for an answer for hours now and haven't found anything to help me.

I'm writing a simple application which generates a random string of characters, then appends the string to the URL of an image hosting site - the idea being it's a sort of image roulette. I'm using the following function to verify that the image exists:

private bool ImgVerifier(string url)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = WebRequestMethods.Http.Head;
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            int statusCode = (int)response.StatusCode;

            if (statusCode == 302)
            {
                MessageBox.Show("Status: " + response.StatusCode.ToString() + " at URL: " + url);
                response.Close();
                return false;
            }
            else
            {
                MessageBox.Show("Status: " + response.StatusCode.ToString() + " at URL: " + url);
                response.Close();
                return true;
            }
        }

The issue I have is the function never seems to report anything other than an HTTP "OK" status. When checking the image URL on the SeoBook Server Header Checker site it reports the page as having a 302 error.




Aucun commentaire:

Enregistrer un commentaire