Linux curlコマンドでデータをHTTP POSTする方法とアンパサンド(&)のエスケープについて紹介します。
curlのフォームデータのPOSTには、2つのオプションが使用できます。
fとdです。
これの違いは、fは一つのキーしか送れませんが、dは複数のパラメータを送ることができます。
curl https://example.com/ -X POST -f 'html=hogehogehoge' #=> Ok
curl https://example.com/ -X POST -f 'html=hogehogehoge&fuga=fugafuga' #=> Error
curl https://example.com/ -X POST -d 'html=hogehogehoge' #=> Ok
curl https://example.com/ -X POST -d 'html=hogehogehoge&fuga=fugafuga' #=> Ok
また、”&”をデータの中に含んでいると、&以降が別のキーだと認識されるため、エスケープの必要があります。
curl https://example.com/ -X POST -d 'html=hogehogehoge&fugafugafuga'
こうするればエスケープと同時にcurlすることができます。
curl https://example.com/ -X POST --data-urlencode 'html=hogehogehoge&fugafugafuga'
複数パラメーターを指定したい場合はオプションを複数指定します。
curl https://example.com/ -X POST --data-urlencode 'html=hogehogehoge&fugafugafuga' --data-urlencode 'hoge=hoge'
もしくは、こちらのスクリプトを使用します。
Bash urlencode and urldecode
urlencode 'hogehogehoge&fugafugafuga'
hogehogehoge%26fugafugafuga
curl https://example.com/ -X POST -d 'html=hogehogehoge%26fugafugafuga'