检测404而不捕获异常

时间:2010-10-28 04:55:40

标签: .net vb.net exception-handling httpwebrequest http-status-code-404

简单功能:检查Web服务器是否返回非200 HTTP状态。

Private Function RemoteFileOk(ByVal Url As String) As Boolean
  Dim req As HttpWebRequest = TryCast(WebRequest.Create(Url), HttpWebRequest)
  req.Method = "HEAD"
  Dim rsp As HttpWebResponse = TryCast(req.GetResponse(), HttpWebResponse)
  Return (rsp.StatusCode = HttpStatusCode.OK)
End Function

我是从“this answer”的How to check if a file exits on an webserver by its URL?获得的。

不幸的是,它不起作用:抛出System.Net.WebException,“当url指向不存在的页面时,远程服务器返回错误:(404)Not Found”。我希望能够使用HEAD请求(或类似的东西)探测服务器,然后处理404而不必捕获异常。

我的解决方案如下:

Private Function RemoteFileOk(ByVal Url As String) As Boolean
  Dim req As HttpWebRequest = TryCast(WebRequest.Create(Url), HttpWebRequest)
  req.Method = "HEAD"
  Try
    Using rsp As HttpWebResponse = TryCast(req.GetResponse(), HttpWebResponse)
      Return (rsp.StatusCode = HttpStatusCode.OK)
    End Using
  Catch ex As WebException
    Return False
  End Try
End Function

但我似乎从不喜欢使用try-catch语句,因为它们可以可以避免使用。

还有另一种,整洁的方式吗?

1 个答案:

答案 0 :(得分:0)

您可以更新您的代码以使用.net 4.5中新的System.Net.Http API,它不会引发这个令人烦恼的异常(请参阅问题的评论)。测试在VS 2012u2下工作。

Private Function RemoteFileOk(ByVal Url As String) As Boolean
    Using client As New HttpClient,
        responseTask As Task(Of HttpResponseMessage) = client.GetAsync(Url, HttpCompletionOption.ResponseHeadersRead)
        responseTask.Wait()
        Using response As HttpResponseMessage = responseTask.Result
            Return response.IsSuccessStatusCode
        End Using
    End Using
End Function

当问到这个问题时,这个答案是不可用的,对于很多人来说,这不是一个解决方案,因为这个API是在.net 4.5中引入的。