How to consume HttpClient from F#?

后端 未结 5 1787
攒了一身酷
攒了一身酷 2021-02-20 04:13

I\'m new to F# and stuck in understanding async in F# from the perspective of a C# developer. Say having the following snippet in C#:



        
5条回答
  •  北恋
    北恋 (楼主)
    2021-02-20 04:57

    Just my two cents. But my understanding is that we should be handling the HttpRequestException when using EnsureSuccessStatusCode().

    Below is the start of a module wrapping HttpClient that will buffer the response of a URL into a string and safely wrap in a Result<'a, 'b> for improved fault tolerance.

    module Http =
        open System    
        open System.Net.Http
    
        let getStringAsync url =
            async {
                let httpClient = new HttpClient() 
                // This can be easily be made into a HttpClientFactory.Create() call
                // if you're using >= netcore2.1
    
                try 
                    use! resp = httpClient.GetAsync(Uri(url), HttpCompletionOption.ResponseHeadersRead) |> Async.AwaitTask                       
                    resp.EnsureSuccessStatusCode |> ignore
    
                    let! str = resp.Content.ReadAsStringAsync() |> Async.AwaitTask
                    return Ok str
                with
                | :? HttpRequestException as ex -> return ex.Message |> Error
            }
    

提交回复
热议问题