LoginSignup
1
2

More than 1 year has passed since last update.

curlでJSONをPOSTするとPowerShellの時だけエラー

Last updated at Posted at 2022-03-31

はじめに

Windows上から curl.exe を利用してJSONをPOSTする際に、
コマンドプロンプト(cmd) 上で実行するとアクセスが成功するのに、
PowerShell 上で実行すると何故かエラーになってしまう。
そんな時の回避方法をご紹介します。

回避方法

PowerShell 上で curl.exe からJSONをPOSTする際は、
下記の様に JSONの値を「シングルクォート」で囲む とアクセスが成功します。

curl.exe --data '"{\"id\": \"123\",\"name\": \"taro\"}"' ~

curl.exe --data シングルクォート + ダブルクォート + JSON(「"」を「\"」に置き換え) + ダブルクォート + シングルクォート

修正前(コマンドプロンプトだと成功するが、PowerShellから実行するとエラー)
curl.exe --data "{\"id\": \"123\",\"name\": \"taro\"}" --verbose --request POST --url "http://localhost:8080/api/test"
修正後(PowerShellから実行すると成功、JSONの値を「シングルクォート」で囲む)
curl.exe --data '"{\"id\": \"123\",\"name\": \"taro\"}"' --verbose --request POST --url "http://localhost:8080/api/test"

補足

PowerShellの場合は、JSONの値を「シングルクォート」で囲まないと、--data "{\"と認識されてしまい、サーバに送信されるリクエストJSONが{\だけとなります。

または、下記の様にJSONのデータをファイル指定(--data '@ファイルパス')にしても同様の動きとなります。

JSONをファイルから読み込む
curl.exe --data '@data.json' --verbose --request POST --url "http://localhost:8080/api/test"
data.json
{
    "id": "123",
    "name": "taro"
}

参考資料

1
2
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
1
2