How to use HttpClient from F #?

I'm new to F # and stuck in understanding async in F # from the perspective of a C # developer. Let's say that in C # the following snippet:

var httpClient = new HttpClient(); var response = await httpClient.GetAsync(url); response.EnsureSuccessStatusCode(); string content = await response.Content.ReadAsStringAsync(); 

How to write the same thing in F #?

+11
f # c # -to-f # task-parallel-library async-await
source share
5 answers

Here is a function that should do what you are looking for (note that you will have to wrap the code in an asynchronous calculation expression to use the let! Syntax):

 let getAsync (url:string) = async { let httpClient = new System.Net.Http.HttpClient() let! response = httpClient.GetAsync(url) |> Async.AwaitTask response.EnsureSuccessStatusCode () |> ignore let! content = response.Content.ReadAsStringAsync() |> Async.AwaitTask return content } 
+18
source

You should at least read and know the installed templates in Http.fs if you are doing something with HttpClient in F #.

[Cm. Comments] TL; DR ... but beware of lobes . As @pimbrouwers notes, you shouldn't have to use it, though - subsets and / or developing your own set of helpers in your context may lead you to a more appropriate abstraction (and bring you the benefits of learning along the way).

At this point: F # is considered an idiomatic practice of storing rarely used and / or overly specific helpers in an off-center location.

+7
source

You can use async :

 let readString (url: Uri) = async { let httpClient = new HttpClient(); let! response = httpClient.GetAsync(url) |> Async.AwaitTask response.EnsureSuccessStatusCode() |> ignore return! response.Content.ReadAsStringAsync() |> Async.AwaitTask } 
+6
source

Just my two cents. But I understand that we must handle an HttpRequestException when using EnsureSuccessStatusCode() .

The following is the beginning of the migration of the HttpClient module, which buffers the response of the URL into string and safely transfers to Result<'a, 'b> to increase 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 } 
+1
source

Just use FSharp.Control.FusionTasks and you will have clear syntax without |> Async.AwaitTask , like

  let httpClient = new System.Net.Http.HttpClient () let getAsync (url:string) = async { let! response = httpClient.GetAsync url response.EnsureSuccessStatusCode () |> ignore let! content = response.Content.ReadAsStringAsync () return content } 
-one
source

All Articles