如何让 curl 仅输出 http 响应正文(json)而没有其他标头等
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24254064/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to get curl to output only http response body (json) and no other headers etc
提问by Rishi
I am using curl in a bash script to fetch the response of a service as below,
我在 bash 脚本中使用 curl 来获取服务的响应,如下所示,
response=$(curl -isb -H "Accept: application/json" "http://host:8080/some/resource")
Service response is of json type and on browser I could perfectly fine response.
However curl response has other unwanted things (such as set-cookie, content-length header in this case) and sometimes the actual response is eaten up.
服务响应是 json 类型,在浏览器上我可以完美响应。
但是 curl 响应还有其他不需要的东西(例如在这种情况下的 set-cookie、content-length 标头),有时实际的响应会被吃掉。
Here is the output of echo $response>
这是echo $response>的输出
Set-Cookie: rack.session=BAh7CEkiD3Nlc3Npb25faWQGOgZFVEkiRWJlY2JiOTE2M2Q1ZWI4NThjMDdi%0AYjRiOWRjMGMxMGEwYTBkMjE3NmJhZDVjYzY4YjY4ZTlmMTE2ZGVkYWE3MTMG%0AOwBGS
SIJY3NyZgY7AEZJIiVhZmQ2MmUyZGMxMzFmOGEwMjg3NDlhNWM3YmVm%0AN2FjNwY7AEZJIg10cmFja2luZwY7AEZ7B0kiFEhUVFBfVVNFUl9BR0VOVAY7%0AAFRJIi00MTc0OGM2MWNkMzljZTYxNzY3ZjU0
Y2I5OTdiYWRkN2MyNTBkYmU4%0ABjsARkkiGUhUVFBfQUNDRVBUX0xBTkdVQUdFBjsAVEkiLWRhMzlhM2VlNWU2%0AYjRiMGQzMjU1YmZlZjk1NjAxODkwYWZkODA3MDkGOwBG%0A--ee97a62095e7d42129
tontent-Length: 354c8; path=/; HttpOnly
This is breaking my response parsing logic.
I have seen this happening intermittently which is weird.
这打破了我的响应解析逻辑。
我已经看到这种情况间歇性地发生,这很奇怪。
Is there a way to get "only"json response from curl output?
I went through the curl documentation but could not see any thing/ or I could have missed it.
Appreciate any help! Thx
有没有办法从 curl 输出中获得“唯一”的json 响应?
我浏览了 curl 文档,但看不到任何东西/或者我可能会错过它。
感谢任何帮助!谢谢
回答by Remy Lebeau
You are specifying the -ioption:
您正在指定-i选项:
-i, --include
(HTTP) Include the HTTP-header in the output. The HTTP-header includes things like server-name, date of the document, HTTP-version and more...
-i, --include
(HTTP)在输出中包含 HTTP 标头。HTTP 标头包括服务器名称、文档日期、HTTP 版本等内容...
Simply remove that option from your command line:
只需从命令行中删除该选项:
response=$(curl -sb -H "Accept: application/json" "http://host:8080/some/resource")
回答by Victor VIet
#!/bin/bash
req=$(curl -s -X GET http://host:8080/some/resource -H "Accept: application/json") 2>&1
echo "${req}"

