F# POST request with HttpClient

Viewed 377

I'm new to F# and I'm trying understand how to make a POST request with HttpClient. I can make a GET request like this

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
    }

getAsync "www.example.com/action"
|> Async.RunSynchronously
|> printfn "%s"

Now I want to make a POST request with a body containing a simple key value pair (lets say genre : 1). I can create a FormUrlEncodedContent but it takes a KeyValuePair. So also what is the kvp equivalent in F# ?

1 Answers

Here is some sample code to post. You can start with a tuple to key value pairs and then encode the form content

    let initUrl = "https://url/to/post/to"
    let formVals =          [ "field1", "val1" ; "field2","val2" ]
                            |> List.map (fun (x,y) -> new KeyValuePair<string,string>(x,y) )
    let content = new FormUrlEncodedContent(formVals)
    let response = httpClient.PostAsync(initUrl, content).Result.Content.ReadAsStringAsync().Result
Related