0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

curlコマンド UTF-8でエンコード

Posted at

curlコマンドで日本語を含むデータをUTF-8でエンコードして送信するには、以下の方法が効果的です:

  1. ファイルを使用する方法:
    post.json(名前はなんでもいいですが)にUTF-8で書き込み。で、こんなコードを書くと文字化けせずに書き込みができます。
curl -X POST -H "Content-Type: application/json" -d "@post.json" "http://localhost:3000/test" -v

[6]

この方法では、日本語を含むJSONデータをUTF-8でエンコードしたファイルを作成し、そのファイルを-d "@ファイル名"オプションで指定します。

  1. エスケープシーケンスを使用する方法:
    日本語文字列をUnicodeエスケープシーケンスに変換して送信します。例えば:
curl -X POST -H "Content-Type: application/json" -d '{"text":"\u3053\u3093\u306B\u3061\u306F"}' "http://example.com/api"

この方法では、「こんにちは」がUnicodeエスケープシーケンスに変換されています。

  1. Windows環境での注意点:
    Windows のコマンドプロンプトがいまだに SJIS (Shift-JIS) という古い文字コードで動作しているため[4]、追加の対策が必要です。

curl.exe -L yahoo.co.jp -o out.html[8]

このように-oオプションを使用して直接ファイルに出力することで、Windows標準出力の文字コード変換問題を回避できます。

  1. PowerShellを使用する場合:
    japaneseStringは既に文字列なので、コード内でそのまま使用できます。String.getBytes()はプラットフォームのデフォルトエンコーディングを使用してバイト配列を作成します。これがUTF-8でない可能性があります。UTF-8でデコードすると文字化けが発生する可能性があります。

これらの方法を使用することで、curlコマンドで日本語を含むデータをUTF-8でエンコードして正しく送信できます。環境に応じて適切な方法を選択してください。

Citations:
[1] https://apidog.com/jp/blog/curl-utf8-decode-encode/
[2] https://askubuntu.com/questions/1247214/change-the-curl-response-encoding-for-some-characters
[3] https://ja.stackoverflow.com/questions/19068/watson-text-to-speech%E3%81%A7%E6%97%A5%E6%9C%AC%E8%AA%9E%E3%82%92post%E3%81%A7%E9%80%81%E3%82%8B%E6%96%B9%E6%B3%95%E3%82%92%E6%95%99%E3%81%88%E3%81%A6%E4%B8%8B%E3%81%95%E3%81%84
[4] https://qiita.com/yamachan360/items/8c928738289cd518eec8
[5] https://wagavulin.hatenablog.com/entry/2015/10/18/060938
[6] https://cattail.co.jp/techcode/2879/
[7] https://www.codecode.xyz/curl_from_eucjp_to_utf8/
[8] https://qiita.com/yugo-yamamoto/items/19d74869a12d48468a6a
[9] https://stackoverflow.com/questions/24009119/utf-8-encoding-only-some-japanese-characters-are-not-getting-converted
[10] https://github.com/curl/curl/issues/6386
[11] https://uchy.me/blog/2024051003/
[12] https://support.servicenow.com/kb?id=kb_article_view&sysparm_article=KB1080480
[13] https://qiita.com/laf/items/60f147cc736710535154
[14] https://tech.iimon.co.jp/entry/2024/12/13
[15] https://www.luftgarden.jp/blog/63/

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?