elm / http

Make HTTP requests in Elm
https://package.elm-lang.org/packages/elm/http/latest
BSD 3-Clause "New" or "Revised" License
155 stars 46 forks source link

Impossible to specify "Content-Type: application/json;charset=utf-8" when using Http.jsonBody #75

Open Janiczek opened 3 years ago

Janiczek commented 3 years ago

I am developing a REPL-like application for the APL language. It uses UTF-8 characters and the server API requires me to specify the charset:

Content-Type: application/json;charset=utf-8

Otherwise I get output like:

      (+⌿÷≢),¯1+?1000 1000⍴2
NOT PERMITTED: Illegal token
      (+⠌¿Ã ·â ‰¢), ¯1+?1000 1000 ⠍´2

(The last line shows the garbled output.)

I can't do

Http.request
    { method = "POST"
    , headers = [ Http.header "Content-Type" "application/json;charset=UTF-8" ]
    , url = "https://tryapl.org/Exec"
    , body = Http.jsonBody (encodeStateAndInput model.state model.input)
    , expect = Http.expectJson ReceivedResponse stateAndOutputDecoder
    , timeout = Nothing
    , tracker = Nothing
    }

because Http.jsonBody adds its own Content-Type header and this gets sent:

Content-Type: application/json;charset=UTF-8 application/json

I can't keep headers empty and send Content-Type: application/json since that will still result in the garbled output.

So far the only way to get out of this situation is to use stringBody instead of jsonBody and encode the JSON myself.

I believe the correct solution would be to check the Content-Type headers and use only the user-given one if there are multiple, instead of joining it and the jsonBody-given one into one string.