次のような F# っぽい Web リクエスト関数を実装しています。
let request
(httpMethod:string)
(url:string)
(headers:Header list)
(content:Content option)=
let groupHeaders (headers:WebHeaderCollection) =
let d = new Dictionary<string, string list> ()
let addToDict h =
let oldValue = if d.ContainsKey(h) then d.Item(h) else []
d.Item(h) <- oldValue @ [headers.Get h]
headers.AllKeys |> Array.iter addToDict
d |> Seq.map (|KeyValue|) |> Map.ofSeq
async {
let rq = WebRequest.Create(url) :?> HttpWebRequest
rq.Method <- httpMethod
headers
|> List.iter (fun (key, value) -> rq.Headers.Add(key, value) |> ignore )
match content with
| Some (contentType, bytes) ->
rq.ContentType <- contentType
do! rq.GetRequestStream().AsyncWrite(bytes)
| None -> ()
try
use! response = rq.AsyncGetResponse()
let webResponse = response :?> HttpWebResponse
let responseCode = webResponse.StatusCode
let stream = webResponse.GetResponseStream()
let length = webResponse.ContentLength |> int32 //TODO what if the data is bigger then 4GB?
let! bytes = stream.AsyncRead(length)
let respHeaders = groupHeaders webResponse.Headers
return
match webResponse.StatusCode with
| HttpStatusCode.OK -> OK (respHeaders, bytes)
| HttpStatusCode.NotFound -> NotFound
| otherCode -> Error <| otherCode.ToString()
with
| :? WebException as ex ->
return Error <| ex.Status.ToString()
}
問題は、結果を返すページを取得しようとすると (riak
値を取得しようとすると) 、応答ではなくメッセージが返されることです。404
WebException
The remote server returned an error: (404) Not Found.
HttpStatusCode.NotFound
同じURLcurl GET
に対して実行すると、次の結果が得られます。
$ curl -v http://localhost:18098/riak/user/asfasfd?returnbody=true
* About to connect() to localhost port 18098 (#0)
* Trying ::1...
* connected
* Connected to localhost (::1) port 18098 (#0)
> GET /riak/user/asfasfd?returnbody=true HTTP/1.1
> User-Agent: curl/7.27.0
> Host: localhost:18098
> Accept: */*
>
* additional stuff not fine /usr/src/ports/curl/curl-7.27.0-1/src/curl-7.27.0/lib/transfer.c:1037: 0 0
* HTTP 1.1 or later with persistent connection, pipelining supported
< HTTP/1.1 404 Object Not Found
< Server: MochiWeb/1.1 WebMachine/1.9.0 (someone had painted it blue)
< Date: Sun, 28 Oct 2012 05:30:12 GMT
< Content-Type: text/plain
< Content-Length: 10
<
not found
* Connection #0 to host localhost left intact
* Closing connection #0
例外WebException
がスローされる理由はありますか? 404 ページが見つからない状況を特定したい場合、例外メッセージを解析する代わりにどのようなオプションがありますか?