1. Maxim Moiseev
  2. Linq2vk

Source

Linq2vk / src / UserAPI / Common / Net.fs

namespace Linq2vk.Core.Implementation

module Net =
    open System
    open System.IO
    open System.Net

#if ASYNC    
    let getUrlResponse (url:string) =
        async {
            let req = HttpWebRequest.Create(url)
            let! resp = req.AsyncGetResponse()
            return resp :?> HttpWebResponse
        }
   
    let processUrlResponse (url:string) f =
        async {
            let! resp = getUrlResponse url
            return f resp
        }
        
    let requestStream url =
        async {
            let! resp = getUrlResponse url
            return resp.GetResponseStream()
        }
        
    let requestText url =
        async {
            let! resp = getUrlResponse url
            use stream = resp.GetResponseStream()
            use reader = new StreamReader(stream)
            return reader.ReadToEnd()
        }
#endif

    let getUrlResponseSync (url:string) =
        let req = HttpWebRequest.Create(url) :?> HttpWebRequest
        use allDone = new System.Threading.AutoResetEvent(false)
        
        let (resp:WebResponse ref) = ref null
        let onResponse (asyncRes:IAsyncResult) =
            resp := req.EndGetResponse(asyncRes)
            
            let httpResp = !resp :?> HttpWebResponse
            printfn "%A" httpResp.ResponseUri
            
            allDone.Set() |> ignore
            ()
            
        let asyncRes = req.BeginGetResponse(AsyncCallback(onResponse), null)
        
        // TODO: Possible problems with infinite lock.
        allDone.WaitOne() |> ignore
        !resp :?> HttpWebResponse
   
    let processUrlResponseSync (url:string) f =
        let resp = getUrlResponseSync url
        f resp
        
    let requestTextSync url =
        let resp = getUrlResponseSync url
        use stream = resp.GetResponseStream()
        use reader = new StreamReader(stream)
        reader.ReadToEnd()