Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

http

http-post

f#

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?

like image 333
Kevin Cantu Avatar asked Nov 05 '22 00:11

Kevin Cantu


1 Answers

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?

like image 181
wmeyer Avatar answered Nov 09 '22 08:11

wmeyer