我是编程新手,F#是我的第一语言。我目前对.NET API仍然非常不熟悉。
我想编写一个函数,给定一个特定的URL,如果HTTP状态代码是200,则返回TRUE,如果是404,则返回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
但是,我收到以下错误消息:
未定义名称空间或模块“HttpWebRequest”
出了什么问题?我应该做些什么改变?
答案 0 :(得分:2)
首先,=
存在轻微问题 - 您必须使用<-
而不使用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
但接下来的问题是,StatusCode
上没有WebResponse
,你必须明确地将其强制转换(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://stackoverflow.com";;
val it : bool = true
> checkIfUrlIsValid "http://stackoverflox.com";;
val it : bool = false
答案 1 :(得分:0)
你必须这样做:
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