【问题标题】:how to pass variable value in POST JSON data in CURL command?如何在 CURL 命令中传递 POST JSON 数据中的变量值?
【发布时间】:2015-01-16 09:13:53
【问题描述】:

有两个字段是唯一的,所以我编写了一个命令来在每次构建 POST 方法时生成随机值,并将这些值存储到变量中,并在 CURL 命令行中传递这些变量。脚本如下。

    rcontactno=$(cat /dev/urandom | tr -dc '0-9' | fold -w 10 | head -n 1)
    rfirstname=$(cat /dev/urandom | tr -dc 'a-zA-Z' | fold -w 10 | head -n 
    echo $rcontactno and $rfirstname
    STATUS=$(curl -v -X POST -d '{"userName":"$rfirstname","contactNo":$rcontactno}' $1/restaurants/53/managers --header "Content-Type:application/json" --header "Accept:application/json" | grep HTTP | cut -d ' ' -f2 )
#Passing the URL using command-line argument    
if [[ STATUS -eq 201 ]]; then
    echo “Success”
    exit 0
    else
    echo “Failed”
    exit 127
    fi

然后我通过

执行脚本

bash manager-post.sh

我遇到这种类型的错误

  > POST /restaurants/53/managers HTTP/1.1
    > User-Agent: curl/7.37.1
    > Host: my-url
    > Content-Type:application/json
    > Accept:application/json
    > Content-Length: 54
    > 
    } [data not shown]
    * upload completely sent off: 54 out of 54 bytes
    < HTTP/1.1 400 Bad Request
    * Server Apache-Coyote/1.1 is not blacklisted
    < Server: Apache-Coyote/1.1
    < Content-Type: application/json;charset=UTF-8
    < Transfer-Encoding: chunked
    < Date: Fri, 16 Jan 2015 08:59:01 GMT
    < Connection: close
    < 
    { [data not shown]
    * Closing connection 0
    “Failed”

但是当我在没有 bash 脚本的情况下运行 curl 命令并明确提及 userName 和 contactNo 的值时,它将成功执行。

我在哪里犯错了?

【问题讨论】:

  • 我使用 URL 作为命令行参数运行 bash 脚本!我也尝试在脚本本身中提及 URL,但输出仍然相同!

标签: bash testing curl http-post


【解决方案1】:

单引号不允许在 shell 中进行变量扩展,因此您需要使用双引号代替。然后您需要随后转义要按原样发送的双引号。

一种有用的调试技术是将--trace-ascii dump.txt 添加到您的命令行并在调用 curl 后检查 dump.txt 以查看它是否与您要发送的内容匹配。

【讨论】:

    猜你喜欢
    • 2020-07-10
    • 2012-10-31
    • 2019-12-19
    • 1970-01-01
    • 2014-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多