简体   繁体   English

如何在Linux中使用curl分别获取http状态代码和内容

[英]How to get http status code and content separately using curl in linux

I have to fetch some data using curl linux utility. 我必须使用curl linux实用程序获取一些数据。 There are two cases, one request is successful and second it is not. 有两种情况,一种是成功的请求,第二种是不成功的。 I want to save output to a file if request is successful and if request is failed due to some reason then error code should be saved only to a log file. 如果请求成功且由于某种原因请求失败,我想将输出保存到文件中,则错误代码应仅保存到日志文件中。 I have search a lot on www but could not found exact solution that's why I have posted a new question on curl. 我在www上进行了大量搜索,但找不到确切的解决方案,这就是为什么我在curl上发布了一个新问题。

curl -I -s -L <Your URL here> | grep "HTTP/1.1"

curl + grep是您的朋友,然后您可以根据需要提取状态代码。

One option is to get the response code with -w, so you could do it something like 一种选择是使用-w获取响应代码,因此您可以执行以下操作

code=$(curl -s -o file -w '%{response_code}' http://example.com/)
if test "$code" != "200"; then
   echo $code >> response-log
else
   echo "wohoo 'file' is fine"
fi

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM