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

自作多情 提交于 2019-12-23 12:47:57

问题


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?


回答1:


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?




回答2:


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



来源:https://stackoverflow.com/questions/5454157/how-can-i-make-an-http-post-request-in-f

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!