curl使用参数引用的方式发送POST请求

  • Bash中的单引号'具有raw字符串的功能,即被单引号'包含的字符串,维持字面意思,其中的$这种特殊字符都不会被解析。
1
2
3
test@runningday ~$echo '$PATH'
$PATH
// $PATH维持字面意思,并没有被解析为变量引用
  • curl发送POST请求时,-d后的json数据,如果含有字符串,必须使用双引号"包裹,不能使用单引号',否则会返回错误码。
1
2
3
4
5
6
7
test@runningday ~$curl -H "Content-Type: application/json" -d "{'app_key': 'key1', 'app_secret': 'secret1'}" https:/open.c.163.com/api/v1/token
{"message":"Unprocessable entity.","code":4220001}
// 其中的payload json数据,全都是用单引号包裹,被报错422

test@runningday ~$curl -H "Content-Type: application/json" -d '{"app_key": "key1", "app_secret": "secret1"}' https:/open.c.163.com/api/v1/token
{"token":"token1","expires_in":"86399"}
// json数据换成用双引号包裹,请求成功
  • 于是乎,如果将上文中json数据的key1secret1使用变量引用的方式,我们就要注意到上文的2个问题,小心谨慎的拼装出最后的命令。
    • 需要保证json数据都由双引号包裹
    • 需要保证$能够被正确解析为变量引用,所以-d的数据整体也要用双引号包裹,而内部需要使用\来进行转义
1
2
3
4
5
6
test@runningday ~$api_prefix="https://open.c.163.com"
test@runningday ~$k1=key1
test@runningday ~$s1=secret1
test@runningday ~$api=${api_prefix}/api/v1/token
test@runningday ~$curl -H "Content-Type: application/json" -d "{\"app_key\": \"${k1}\", \"app_secret\": \"${s1}\"}" ${api}
{"token":"token1","expires_in":"86399"}