Spring Boot の RestTemplate で application/x-www-form-urlencoded な request を送信する
TL; DR
request として渡す Object に
MultiValueMap
を使用すること。application/json
の場合とは異なり、任意の Object を使うことはできない。Java
背景 | 何に困っていたか
RestTemplate に渡す request を作るとき、だいたい以下のような感じの POJO を放り込んでやればよしなにやってくれるイメージだった。
Java
しかし、以下の実装では request が通らなかった。
Java
………🤔
詳細 | 何が起こっていたか
- RestTemplate は、response の Content-Type に応じて適切な
HttpMessageConverter
の実装を選択し、使用する HttpMessageConverter
とは何ぞや?
Strategy interface for converting from and to HTTP requests and responses.
- Content-Type が
application/x-www-form-urlencoded
の場合は、FormHttpMessageConverter
を使用する
FormHttpMessageConverter
は以下のように振る舞う
Implementation ofHttpMessageConverter
to read and write 'normal' HTML forms and also to write (but not read) multipart data (e.g. file uploads). In other words, this converter can read and write the"application/x-www-form-urlencoded"
media type asMultiValueMap<String, String>
, and it can also write (but not read) the"multipart/form-data"
and"multipart/mixed"
media types asMultiValueMap<String, Object>
.
- したがって、いくら任意の POJO を request に渡してもダメ。
MultiValueMap
を使用すること