2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

日本語のパスパラメータをcurlでPOSTするワンライナーを作ってみる

Posted at

概要

パスパラメータ形式のAPIに日本語文字列をPOSTしたい・・
しかし、curl -X POST ${API_ENDPOINT}/あいうえお といった感じでそのまま日本語文字列を埋め込んでリクエストを送ると文字化けしてしまう。

そこで文字列をエンコードした上でリクエストを送信する必要がある。

コマンド

http://localhost:3000/:paramというURIに対して、パラメータ部分に日本語文字列を指定してリクエストを送る

PARAM=$(echo あいうえおかきくけこ | nkf -wMQ | tr = % | tr -d "\n" | tr -s "%%" "%") && curl -X POST http://localhost:3000/$PARAM

nkf -wMQ
日本語をQuoted stream形式でエンコードする
「あ」は=E3という形式で表現される。
パスパラメータの場合、%E3という形で表現する必要がある

tr = %
= を %に置換

tr -d "\n"
文字列が長いと改行されてしまうので、改行コードを削除

tr -s "%%" "%"
文字列が長いと、%% と連続してしまうことがあるので%に置換

エンコードした文字列を日本語に戻す

エンコードした文字列を日本語に戻したいときは以下のコマンドを実行

$ echo $PARAM | tr % = | nkf -WmQ

あいうえおかきくけこ

nkf -WmQ
Quoted stream 形式の文字列を解読する

参考

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?