2011-09-18 78 views
2

我正在尝试做一个简单的函数来验证网站上是否存在特定的文件。验证文件存在于网站上

web请求被设置为头这样我就可以得到,而不是将整个文件下载文件长度,但我得到“无法连接到远程服务器”异常。 如何验证网站上存在的文件?

WebRequest w; 

    WebResponse r; 

    w = WebRequest.Create("http://website.com/stuff/images/9-18-2011-3-42-16-PM.gif"); 
    w.Method = "HEAD"; 
    r = w.GetResponse(); 

编辑:我的坏,事实证明我检查日志后我的防火墙阻止http请求。 它没有提示我一个例外规则,所以我认为这是一个错误。

+2

你知不知道你在说Web服务器是否真正支持HEAD请求?您是否尝试过使用Wireshark来查看网络级别发生了什么? –

+2

我刚刚使用随机URL测试了您的代码片段,并且它可以正常工作。你确定你指定的网址实际上存在吗? –

+0

我同意@Jon,OP应该用GET替代来看看会发生什么。 –

回答

0
try 
{ 
    WebRequest request = HttpWebRequest.Create("http://www.microsoft.com/NonExistantFile.aspx"); 
    request.Method = "HEAD"; // Just get the document headers, not the data. 
    request.Credentials = System.Net.CredentialCache.DefaultCredentials; 
    // This may throw a WebException: 
    using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) 
    { 
     if (response.StatusCode == HttpStatusCode.OK) 
     { 
      // If no exception was thrown until now, the file exists and we 
      // are allowed to read it. 
      MessageBox.Show("The file exists!"); 
     } 
     else 
     { 
      // Some other HTTP response - probably not good. 
      // Check its StatusCode and handle it. 
     } 
    } 
} 
catch (WebException ex) 
{ 
    // Cast the WebResponse so we can check the StatusCode property 
    HttpWebResponse webResponse = (HttpWebResponse)ex.Response; 

    // Determine the cause of the exception, was it 404? 
    if (webResponse.StatusCode == HttpStatusCode.NotFound) 
    { 
     MessageBox.Show("The file does not exist!"); 
    } 
    else 
    { 
     // Handle differently... 
     MessageBox.Show(ex.Message); 
    } 
} 
1

我测试过这一点,它工作正常:

private bool testRequest(string urlToCheck) 
{ 
    var wreq = (HttpWebRequest)WebRequest.Create(urlToCheck); 

    //wreq.KeepAlive = true; 
    wreq.Method = "HEAD"; 

    HttpWebResponse wresp = null; 

    try 
    { 
     wresp = (HttpWebResponse)wreq.GetResponse(); 

     return (wresp.StatusCode == HttpStatusCode.OK); 
    } 
    catch (Exception exc) 
    { 
     System.Diagnostics.Debug.WriteLine(String.Format("url: {0} not found", urlToCheck)); 
     return false; 
    } 
    finally 
    { 
     if (wresp != null) 
     { 
      wresp.Close(); 
     } 
    } 
} 

试试这个网址:http://www.centrosardegna.com/images/losa/losaabbasanta.png然后修改图像名称,它会返回false。 ;-)