How can I make an HTTP POST request in F#?

2019-06-27 20:55发布

The following code sends a GET request. This is making me crazy.

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

At the moment I'm not sure that anyone has ever used F# to send an HTTP POST. Has anyone seen documentation about this?

2条回答
倾城 Initia
2楼-- · 2019-06-27 21:28

Seems to work fine for me. For example (posttestserver.com does really exist):

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

Result:

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

Maybe you are using it in a different way?

查看更多
Explosion°爆炸
3楼-- · 2019-06-27 21:29

I found one MSDN article about Request-Response Testing With F#

查看更多
登录 后发表回答