F#:检查是否 URL returns HTTP 错误 404

F#: Checking whether a URL returns HTTP Error 404

我是编程新手,F# 是我的第一语言。我目前对.NET API 还很陌生。

我想编写一个函数,给定一个特定的 URL,如果 HTTP 状态代码为 200,则 return 为 TRUE,如果为 404,则 return FALSE。

这是我写的代码:

open System.Net

let checkIfUrlIsValid (url: string) =
    try
        let webRequest = HttpWebRequest.Create(url)
        let webRequest.Method = "HEAD"
        use webResponse = webRequest.GetResponse()
        webResponse.StatusCode = HttpStatusCode.OK
    with
        :? System.Net.WebException -> false

但是,我收到以下错误消息:

The namespace or module 'HttpWebRequest' is not defined

出了什么问题?我应该做哪些改变?

你必须这样做:

open System.Net

let checkIfUrlIsValid (url: string) =
   try
      let mutable  webRequest = HttpWebRequest.Create(url)
      webRequest.Method <- "HEAD"
      use webResponse = webRequest.GetResponse() :?> HttpWebResponse
      webResponse.StatusCode = HttpStatusCode.OK
   with
      :? System.Net.WebException -> false

首先那里的 = 有一个小问题 - 你必须使用 <- 而没有 let 来改变值:

open System.Net

let checkIfUrlIsValid (url: string) =
    try
        let webRequest = HttpWebRequest.Create(url)
        webRequest.Method <- "HEAD"
        use webResponse = webRequest.GetResponse()
        // ...
    with
        :? System.Net.WebException -> false

但下一个问题是,WebResponse 上没有 StatusCode,你必须明确地转换它(到 HttpWebResponse),所以这最终应该可以工作:

open System.Net

let checkIfUrlIsValid (url: string) =
    try
        let webRequest = HttpWebRequest.Create(url)
        webRequest.Method <- "HEAD"
        use webResponse = webRequest.GetResponse() :?> HttpWebResponse
        webResponse.StatusCode = HttpStatusCode.OK
    with
        :? System.Net.WebException -> false

这里做个小测试-运行 ;)

> checkIfUrlIsValid "http://whosebug.com";;
val it : bool = true
> checkIfUrlIsValid "http://stackoverflox.com";;
val it : bool = false