Call Url to check the content type?

Do I need to check if the content type is a PDF URL or not? I have working code, but I was wondering what is the best way to check what I have. I don’t need to display the PDF file, I just need to check if the content type of the PDF is a file or not? Note. This method will be called multiple times with a different url, so I'm not sure if I need to close the answer or not.

here is my code.

private bool IsValid(string url) { bool isValid = false; var request = (HttpWebRequest)WebRequest.Create(url); var response = (HttpWebResponse)request.GetResponse(); if(response.StatusCode == HttpStatusCode.OK && response.ContentType == "application/pdf") { isValid = true; } response.Close(); return isValid; } 
+4
source share
1 answer

Yes, since you do not pass response anywhere you need to dispose of it. You should also catch a WebException and remove the stream from there too (I would also expect that a delete response or even a request would close all related resources, but unfortunately I have never seen documentation that confirms this cascading delete behavior for a Response object) .

You also need to close / delete the request, as it is a one-time object. This is indicated in the GetResponse note:

Multiple GetResponse calls return the same response object; The request has not been reissued.

Side note. Consider requesting a HEAD so that you don't receive a stream at all (see Method Property to Use).

 var request = (HttpWebRequest)WebRequest.Create(url); request.Method = "HEAD"; 
+7
source

Source: https://habr.com/ru/post/1441852/


All Articles