Invoke Url to check content type?

2019-06-25 14:35发布

问题:

I need to check if the url content type is pdf or not? I have a working code however i was wondering what's the best way to check from what i have. I don't need to display the pdf, just need to check if the content type is pdf or not? Note: This method will be called multiple times with different url, so i am not sure if i need to close the response 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;
}

回答1:

Yes as you don't pass response anywhere you need to dispose it. You should also catch WebException and dispose stream from there too (also I would expect disposing response or even request would close all related resource, but unfortunately I never seen documentation that confirms such cascading dispose behavior for Response object).

You also need to close/dispose the request as it is one-use object. It is specified in note of GetResponse:

Multiple calls to GetResponse return the same response object; the request is not reissued.

Side note: Consider making HEAD request so you don't get any stream at all (see Method property for usage).

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