如何在F#中发出HTTP POST请求?

时间:2011-03-28 02:48:45

标签: http f# http-post

以下代码发送GET请求。这让我很疯狂。

let postDocRaw (url:string) (data: string) : string =
      let data' : byte[] = System.Text.Encoding.ASCII.GetBytes(data);

      let request = WebRequest.Create(url)
      request.Method        <- "POST"
      request.ContentType   <- "application/x-www-form-urlencoded"
      request.ContentLength <- (int64) data'.Length

      use wstream = request.GetRequestStream() 
      wstream.Write(data',0, (data'.Length))
      wstream.Flush()
      wstream.Close()
(*
      use writer = new StreamWriter (wstream) 
      writer.Write(data')
      writer.Flush()
      writer.Close()
*)

      let response  = request.GetResponse()
      use reader     = new StreamReader(response.GetResponseStream())
      let output = reader.ReadToEnd()

      reader.Close()
      response.Close()
      request.Abort()

      output

目前我不确定是否曾有人使用F#发送HTTP POST。有没有人见过这方面的文件?

2 个答案:

答案 0 :(得分:2)

似乎对我来说很好。例如(posttestserver.com确实存在):

printfn "response: %A" (postDocRaw "http://posttestserver.com/post.php" "hello=data")
Console.ReadLine() |> ignore

结果:

response: "
Successfully dumped 1 post variables.Post body was 0 chars long.
"

也许你以不同的方式使用它?

答案 1 :(得分:0)

我找到了一篇关于Request-Response Testing With F#

的MSDN文章