首页 > 解决方案 > curl 命令有效负载中字符串的脚本连接

问题描述

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", \

我怀疑它与 in 的空间displayName以及我如何插入displayNameusing的值有关"'$NEWUSERDISPLAYNAME'"curl在命令的 POST 请求有效负载中执行变量替换是否有安全的方法?

标签: bashshellcurlstring-concatenation

解决方案


您需要引用 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"

推荐阅读