bash 使用 CURL 下载文件并查看标题和状态代码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/11836238/
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
Using CURL to download file and view headers and status code
提问by curtisdf
I'm writing a Bash script to download image files from Snapito's web page snapshot API. The API can return a variety of responses indicated by different HTTP response codes and/or some custom headers. My script is intended to be run as an automated Cron job that pulls URLs from a MySQL database and saves the screenshots to local disk.
我正在编写一个 Bash 脚本来从Snapito的网页快照 API下载图像文件。API 可以返回由不同的 HTTP 响应代码和/或一些自定义标头指示的各种响应。我的脚本旨在作为自动 Cron 作业运行,该作业从 MySQL 数据库中提取 URL 并将屏幕截图保存到本地磁盘。
I am using curl.  I'd like to do these 3 things using a single CURL command:
我正在使用curl. 我想使用单个 CURL 命令来完成这 3 件事:
- Extract the HTTP response code
 - Extract the headers
 - Save the file locally (if the request was successful)
 
- 提取 HTTP 响应代码
 - 提取标题
 - 将文件保存在本地(如果请求成功)
 
I could do this using multiple curlrequests, but I want to minimize the number of times I hit Snapito's servers.  Any curlexperts out there?
我可以使用多个curl请求来做到这一点,但我想尽量减少我访问 Snapito 服务器的次数。任何curl专家在那里?
Or if someone has a Bash script that can respond to the full documented set of Snapito API responses, that'd be awesome. Here's their API documentation.
或者,如果有人有一个 Bash 脚本可以响应完整记录的 Snapito API 响应集,那就太棒了。这是他们的 API 文档。
Thanks!
谢谢!
回答by WA Hunt
Use the dump headers option:
curl -D /tmp/headers.txt http://server.com
使用转储标头选项:
curl -D /tmp/headers.txt http://server.com
回答by Guy Adini
Use curl -i(include HTTP header) - which will yield the headers, followed by a blank line, followed by the content.
使用curl -i(包括 HTTP 标头) - 这将产生标头,后跟一个空行,然后是内容。
You can then split out the headers / content (or use -D to save directly to file, as suggested above).
然后,您可以拆分标题/内容(或使用 -D 直接保存到文件,如上所述)。
There are three options -i, -I, and -D
有 3 个选项-i,-I, 和-D
> curl --help | egrep '^ +\-[iID]'
 -D, --dump-header FILE  Write the headers to FILE
 -I, --head          Show document info only
 -i, --include       Include protocol headers in the output (H/F)

