bash - 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
以及我如何插入displayName
using的值有关"'$NEWUSERDISPLAYNAME'"
。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"
推荐阅读
- java - 为什么在整个测试过程中没有保持主要活动?
- c# - 使用连接而不指定所有属性
- python - 如何在python中从多个PDF中返回所有提取的文本?
- python-3.x - 根据字典列表和特定日期条件替换列值 - Pandas
- python - 使用 Python 进行异步日志记录
- spring-boot - Keycloak:用于检查用户令牌是否具有特定资源角色的 API
- firebase - 使用颤振挑选和发布多张图片和视频
- android - Flutter 应用程序在调试中工作,但在发布时崩溃
- c# - 检查数据库中是否已存在列表项的最佳方法是什么?
- python - 有什么方法可以将 pandas 等 python 库用于 Sikuli 脚本?或者我可以通过任何 python 解释器运行 Sikuli .py 文件吗?