こまメモ

Twitter以上技術ブログ未満

java.net.URLEncoder#encode はスペース(' ')をプラス('+')に変換する

URLエンコーディングでスペースは何に変換されるか

URLエンコーディングでは、スペース(' ')はプラス('+')に変換されるパターンと '%20' に変換されるパターンの2つがある。

Depending on the context, the character ' ' is translated to a '+' (like in the percent-encoding version used in an application/x-www-form-urlencoded message), or in '%20' like on URLs.

developer.mozilla.org

Javaの場合

Javaの標準APIにある java.net.URLEncoder#encode では、application/x-www-form-urlencoded形式を採用しており、'+'に変換される。

Translates a string into application/x-www-form-urlencoded format using a specific encoding scheme.

docs.oracle.com

もし、'%20' に変換してほしいのであれば、 encode をしたあとで、 replace("+", "%20") するのが手っ取り早い。

.NETの場合

.NET だと %20 に直接変換してくれるメソッドが用意されている模様。

You can encode a URL using with the UrlEncode method or the UrlPathEncode method. However, the methods return different results. The UrlEncode method converts each space character to a plus character (+). The UrlPathEncode method converts each space character into the string "%20", which represents a space in hexadecimal notation. Use the UrlPathEncode method when you encode the path portion of a URL in order to guarantee a consistent decoded URL, regardless of which platform or browser performs the decoding.

learn.microsoft.com