代码之家  ›  专栏  ›  技术社区  ›  Web User

curl命令负载中字符串的脚本连接

  •  1
  • Web User  · 技术社区  · 8 年前

    我用 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”)

    但是我从服务器上得到一个异常,因为 卷曲 命令似乎被切断、不完整或格式不正确。

    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\"])"
    

    如果我硬编码值 displayName 在上面的curl命令(如下所示)中,用户创建请求完成并完美工作。

    "displayName": "John Doe", \
    

    我想这和里面的空间有关 显示名称 以及如何为 显示名称 使用 "'$NEWUSERDISPLAYNAME'" . 在 卷曲 命令的请求后有效载荷?

    1 回复  |  直到 8 年前
        1
  •  3
  •   anubhava    8 年前

    您需要引用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"
    
    推荐文章