Skip to content

req_body_raw blocks setting the Content-Type header #116

@colmanhumphrey

Description

@colmanhumphrey

NOTE: LOW PRIORITY

I could have this wrong, and/or this could be intended behaviour.

In trying to send a top-level empty list (see #115), I figured I could create the required JSON myself and use req_body_raw. I didn't see at first that this function takes a type, and I first set the header, that is:

library(httr2)

url <- "http://httpbin.org/"
req <- request(url)

body <- req |>
    req_body_raw("{\"empty_list\":[]}") |>
    req_headers("Content-Type" = "application/json") |>
    req_dry_run()

#> POST / HTTP/1.1
#> Host: httpbin.org
#> User-Agent: httr2/0.1.1 r-curl/4.3.2 libcurl/7.77.0
#> Accept: */*
#> Accept-Encoding: deflate, gzip
#> Content-Length: 17
#> 
#> {"empty_list":[]}

But this doesn't set Content-Type: application/json. I am a little surprised that the header call coming after the body doesn't "win" the header battle.

This also isn't resolved by setting the header before the req_body_raw call (or by setting both).

As expected, all works if the type parameter of req_body_raw is used instead of setting the header:

library(httr2)

url <- "http://httpbin.org/"
req <- request(url)

body <- req |>
    req_body_raw("{\"empty_list\":[]}", type = "application/json") |>
    req_dry_run()
#> POST / HTTP/1.1
#> Host: httpbin.org
#> User-Agent: httr2/0.1.1 r-curl/4.3.2 libcurl/7.77.0
#> Accept: */*
#> Accept-Encoding: deflate, gzip
#> Content-Type: application/json
#> Content-Length: 17
#> 
#> {"empty_list":[]}
Session Info
> sessionInfo()
R version 4.1.2 (2021-11-01)
Platform: aarch64-apple-darwin20 (64-bit)
Running under: macOS Monterey 12.1

Matrix products: default
BLAS:   /Library/Frameworks/R.framework/Versions/4.1-arm64/Resources/lib/libRblas.0.dylib
LAPACK: /Library/Frameworks/R.framework/Versions/4.1-arm64/Resources/lib/libRlapack.dylib

locale:
[1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
[1] jsonlite_1.7.2   httr2_0.1.1      conflicted_1.0.4

loaded via a namespace (and not attached):
 [1] Rcpp_1.0.8.3     crayon_1.4.2     later_1.3.0      rappdirs_0.3.3  
 [5] R6_2.5.1         magrittr_2.0.1   rlang_1.0.2      cachem_1.0.6    
 [9] cli_3.1.0        curl_4.3.2       promises_1.2.0.1 tools_4.1.2     
[13] glue_1.5.1       httpuv_1.6.5     fastmap_1.1.0    compiler_4.1.2  

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugan unexpected problem or unintended behavior

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions