2011-03-28 54 views
3

以下代碼發送GET請求。這讓我發瘋。如何在F#中創建HTTP POST請求?

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

似乎爲我工作的罰款。例如(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. 
" 

也許你正在以不同的方式使用它嗎?

+0

嗯,我不是說這是一個詭計問題。我不確定我是否明白髮生了什麼問題,但通過改變我稱之爲的方式,我已經完成了一些工作......謝謝! – 2011-03-28 04:16:36

+0

如何在上面的例子中設置Accept頭? – App2015 2018-03-08 14:34:57