我使用 curl
来测试用户帐户创建 API,如下所示:
curl -s -X POST "https://$APISERVER/users" \
-H 'Content-Type: application/json' \
-d '{ \
"username": "'$NEWUSERNAME'", \
"firstName": "'$NEWUSERFIRSTNAME'", \
"lastName": "'$NEWUSERLASTNAME'", \
"displayName": "'$NEWUSERDISPLAYNAME'", \
"password": "'$NEWUSERPASSWORD'" \
}'
并且变量是通过命令行参数提供的:
APISERVER=http://localhost:8080
NEWUSERNAME=$1
NEWUSERPASSWORD=$2
NEWUSERFIRSTNAME=$3
NEWUSERLASTNAME=$4
# Calculated variable
NEWUSERDISPLAYNAME="${NEWUSERFIRSTNAME} ${NEWUSERLASTNAME}"
脚本调用示例如下:./test-new-user.sh jdoe Hello123 John Doe
,产生以下变量值:
NEWUSERNAME=jdoe
NEWUSERPASSWORD=Hello123
NEWUSERFIRSTNAME=John
NEWUSERLASTNAME=Doe
(我打算将 NEWUSERDISPLAYNAME
设置为“John Doe”)
但我从服务器返回了一个异常,因为 curl
命令中的有效负载似乎被截断、不完整或格式错误。
JSON parse error: Unexpected end-of-input in VALUE_STRING\n at [Source:
java.io.PushbackInputStream@2eda6052; line: 1, column: 293]; nested
exception is com.fasterxml.jackson.databind.JsonMappingException:
Unexpected end-of-input in VALUE_STRING\n at [Source:
java.io.PushbackInputStream@2eda6052; line: 1, column: 293]\n at
[Source: java.io.PushbackInputStream@2eda6052; line: 1, column: 142]
(through reference chain:
com.mycompany.api.pojos.NewUser[\"displayName\"])"
如果我在上面的 curl 命令中硬编码 displayName
的值(如下所示),用户创建请求将通过并完美运行。
"displayName": "John Doe", \
我怀疑这与 displayName
中的空格以及我如何使用 "'$NEWUSERDISPLAYNAME'"
插入 displayName
的值有关.在 curl
命令的 POST 请求负载中执行变量替换是否有安全的方法?
最佳答案
您需要引用 shell 变量:
curl -s -X POST "https://$APISERVER/users" \
-H 'Content-Type: application/json' \
-d '{ \
"username": "'"$NEWUSERNAME"'", \
"firstName": "'"$NEWUSERFIRSTNAME"'", \
"lastName": "'"$NEWUSERLASTNAME"'", \
"displayName": "'"$NEWUSERDISPLAYNAME"'", \
"password": "'"$NEWUSERPASSWORD"'" \
}'
为了避免过多引用,试试这个 printf
:
printf -v json -- '{ "username": "%s", "firstName": "%s", "lastName": "%s", "displayName": "%s", "password": "%s" }' \
"$NEWUSERNAME" "$NEWUSERFIRSTNAME" "$NEWUSERLASTNAME" "$NEWUSERDISPLAYNAME" "$NEWUSERPASSWORD"
curl -s -X POST "https://$APISERVER/users" \
-H 'Content-Type: application/json' \
-d "$json"
关于bash - curl 命令负载中字符串的脚本连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50613030/