r-lib / httr

httr: a friendly http package for R
https://httr.r-lib.org
Other
986 stars 1.99k forks source link

Send array in POST request with encode = "form" #676

Closed selesnow closed 1 year ago

selesnow commented 4 years ago

Hello Hadley!

your example in Getting started with httr

url <- "http://httpbin.org/post"
body <- list(a = 1, b = 2, c = 3)

# Form encoded
r <- POST(url, body = body, encode = "form")

How i can send next request?

url <- "http://httpbin.org/post"
body <- list(`a[]` = c(1, 2, 3))

# Form encoded
r <- POST(url, body = body, encode = "form")

When i try this i got error:

Error in vapply(elements, encode, character(1)) : 
  values must be length 1,
 but FUN(X[[1]]) result is length 3

But when i try:

body <- list(`a[]` = 1, `a[]` = 2, `a[]` = 3)
# Form encoded
r <- POST(url, body = body, encode = "form")

All works correctly.

How i can send list of values with encode = "form" ?

olololyaa commented 1 year ago

Hi @selesnow, have you managed to find a solution?

ekianjo commented 1 year ago

interested to know the solution as well - fails in this kind of case with httr

hadley commented 1 year ago

If I understand correctly what you want, you can do this with httr2 as follows:

library(httr2)

request("http://httpbin.org/post") |> 
  req_body_form(a = 1, a = 2, a = 3) |> 
  req_dry_run()
#> POST /post HTTP/1.1
#> Host: httpbin.org
#> User-Agent: httr2/0.2.3.9000 r-curl/5.1.0 libcurl/8.1.2
#> Accept: */*
#> Accept-Encoding: deflate, gzip
#> Content-Type: application/x-www-form-urlencoded
#> Content-Length: 11
#> 
#> a=1&a=2&a=3

Created on 2023-10-31 with reprex v2.0.2

httr has been superseded in favour of httr2, so is no longer under active development.