Spring Boot の RestTemplate で application/x-www-form-urlencoded な request を送信する

 

TL; DR

request として渡す Object に MultiValueMap を使用すること。
application/json の場合とは異なり、任意の Object を使うことはできない。
Java
 

背景 | 何に困っていたか

 
RestTemplate に渡す request を作るとき、だいたい以下のような感じの POJO を放り込んでやればよしなにやってくれるイメージだった。
Java
 
しかし、以下の実装では request が通らなかった。
Java
 
………🤔

詳細 | 何が起こっていたか

 
  1. RestTemplate は、response の Content-Type に応じて適切な HttpMessageConverter の実装を選択し、使用する
    1. HttpMessageConverter とは何ぞや?
      1. Strategy interface for converting from and to HTTP requests and responses.
  1. Content-Type が application/x-www-form-urlencoded の場合は、FormHttpMessageConverter を使用する
  1. FormHttpMessageConverter は以下のように振る舞う
    1. Implementation ofHttpMessageConverterto 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 as MultiValueMap<String, String>, and it can also write (but not read) the "multipart/form-data" and "multipart/mixed" media types as MultiValueMap<String, Object>.
  1. したがって、いくら任意の POJO を request に渡してもダメ。 MultiValueMap を使用すること