curl命令有效负载

时间:2018-05-30 20:39:58

标签: bash shell curl string-concatenation

我使用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中的空格有关,以及我如何使用displayName插入"'$NEWUSERDISPLAYNAME'"的值。有没有一种安全的方法在curl命令的POST请求有效负载中执行变量替换?

1 个答案:

答案 0 :(得分:3)

您需要引用shell变量:

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"

    using (var workbook = new XLWorkbook())
    {
        workbook.Properties.Author = "Me";
        workbook.Properties.Title = "Title";
        var worksheet = workbook.AddWorksheet("Sheet 1");
        worksheet.Row(1).Cell(1).SetValue("test");
        workbook.SaveAs("c:\\temp\\testing.xlsx");
    }