02


SUBMITTED BY: Guest

DATE: Nov. 10, 2013, 4:46 p.m.

FORMAT: Text only

SIZE: 2.7 kB

HITS: 4393

  1. Some sw
  2. use sw = new StreamWriter(fileName)
  3. let! response = Http.InnerRequest(url, true, ?headers=headers, ?query=query, ?meth=meth, ?body=body, ?cookies=cookies, ?cookieContainer=cookieContainer, ?certificate=certificate, ?streamWriter=Some sw)
  4. /// Read the contents of a stream asynchronously and return it as a string
  5. static let asyncReadToEnd (stream:Stream) isText streamWriter = async {
  6. // Allocate 4kb buffer for downloading dat
  7. let buffer = Array.zeroCreate (4 * 1024)
  8. use output =
  9. match streamWriter with
  10. | Some (sw) -> sw
  11. | None -> new MemoryStream()
  12. let reading = ref true
  13. ....
  14. static member private InnerRequest(url:string, forceText, ?query, ?headers, ?meth, ?body, ?cookies, ?cookieContainer, ?certificate, ?streamWriter) = async {
  15. ....
  16. return! Http.augmentWebExceptionsWithDetails <| fun () -> async {
  17. use! resp = Async.FromBeginEnd(req.BeginGetResponse, req.EndGetResponse)
  18. use stream = resp.GetResponseStream()
  19. let! respBody = asyncReadToEnd stream (forceText || (isText resp.ContentType)) streamWriter
  20. let cookies = Map.ofList [ for cookie in cookieContainer.GetCookies uri |> Seq.cast<Cookie> -> cookie.Name, cookie.Value ]
  21. let headers = Map.ofList [ for header in resp.Headers.AllKeys -> header, resp.Headers.[header] ]
  22. let statusCode =
  23. match resp with
  24. | :? HttpWebResponse as resp -> int resp.StatusCode
  25. | _ -> 0
  26. return { Body = respBody
  27. Headers = headers
  28. ResponseUrl = resp.ResponseUri.OriginalString
  29. Cookies = cookies
  30. StatusCode = statusCode } }
  31. }
  32. static member AsyncRequestFile(url, (fileName:string), ?query, ?headers, ?meth, ?body, ?cookies, ?cookieContainer, ?certificate) = async {
  33. use sw = new StreamWriter(fileName)
  34. let! response = Http.InnerRequest(url, true, ?headers=headers, ?query=query, ?meth=meth, ?body=body, ?cookies=cookies, ?cookieContainer=cookieContainer, ?certificate=certificate, ?streamWriter=Some sw)
  35. return
  36. match response.Body with
  37. | ResponseBody.Text text -> text
  38. | ResponseBody.Binary binary -> failwithf "Expecting text, but got a binary response (%d bytes)" binary.Length
  39. }
  40. use output =
  41. match streamWriter with
  42. | Some (sw) -> sw
  43. | None -> new MemoryStream()

comments powered by Disqus