Nip*_*ara 4 shell curl http-headers access-token
我试图运行一个 shell 脚本,其中包含一个 curl 命令,其所需的标题如下。
counter=1
H1='Content-Type: application/json'
H2='Accept: application/json'
H3='Authorization: Bearer a0a9bb26-bb7d-3645-9679-2cd72e2b4c57'
URL='http://localhost:8280/mbrnd_new/v1/post'
while [ $counter -le 10 ]
do
TEST="curl -X POST --header $H1 --header $H2 --header $H3 -d @s_100mb.xml $URL"
echo $TEST
RESPONSE=`$TEST`
echo $RESPONSE
sleep 5
done
echo "All done"
Run Code Online (Sandbox Code Playgroud)
它给出了一个错误
curl: (6) Could not resolve host: application
curl: (6) Could not resolve host: Bearer
curl: (6) Could not resolve host: a0a9bb26-bb7d-3645-9679-2cd72e2b4c57
<ams:fault xmlns:ams="http://wso2.org/apimanager/security"><ams:code>900902</ams:code><ams:message>Missing Credentials</ams:message><ams:description>Required OAuth credentials not provided. Make sure your API invocation call has a header: "Authorization: Bearer ACCESS_TOKEN"</ams:description></ams:fault>
Run Code Online (Sandbox Code Playgroud)
给定的访问令牌和其他标头参数是正确的。当直接调用 'curl' 时它工作正常。
我尝试了使用 \" 等不同的方法,但没有任何效果。如果有人能对此提供正确的答案,我将不胜感激。
谢谢。
您要执行的命令类似于:
curl -X POST --header "$H1" --header "$H2" --header "$H3" -d @s_100mb.xml "$URL"
Run Code Online (Sandbox Code Playgroud)
(我会用-H而不是--header因为它更短。)
最简单的方法是
response=$(curl -X POST -H "$H1" -H "$H2" -H "$H3" -d @s_100mb.xml "$URL")
Run Code Online (Sandbox Code Playgroud)
您的解决方案的问题在于您根本没有分隔标头值:
curl -X POST -H $H1
Run Code Online (Sandbox Code Playgroud)
如果内容H1是foo: bar,那么这将扩展为
curl -X POST -H foo bar
Run Code Online (Sandbox Code Playgroud)
这将被解释为
curl -X POST -H (foo:) bar
Run Code Online (Sandbox Code Playgroud)
(使用(and)仅用于说明优先级,在 shell 中没有类似的东西),bar即将被视为第一个位置参数,它恰好是主机名,导致您看到的奇怪错误。
你想要的是
curl -X POST -H (foo: bar)
Run Code Online (Sandbox Code Playgroud)
这可以通过将扩展正确包装在引号中来实现,如上所示。
此外,您应该更喜欢 $(cmd) 到 `cmd`。
作为最后一条建议,如果您正在学习如何使用 shell,那么避免多次扩展可能是明智的,即以后不要将您的命令存储在CMD变量中$($CMD),因为这会导致在多个地方进行多次扩展(第一个CMD被分配到哪里,第二个CMD是在$(...)子 shell 中展开时),这让人很难理解到底发生了什么。