我使用curl来获取http报头以查找http状态代码并返回响应。我使用命令获取http头信息
curl -I http://localhost
为了得到响应,我使用命令
curl http://localhost
一旦使用了-I标志,我就只得到了头信息,响应就不再存在了。是否有一种方法可以同时获得http响应和头/http状态码在一个命令?
我使用curl来获取http报头以查找http状态代码并返回响应。我使用命令获取http头信息
curl -I http://localhost
为了得到响应,我使用命令
curl http://localhost
一旦使用了-I标志,我就只得到了头信息,响应就不再存在了。是否有一种方法可以同时获得http响应和头/http状态码在一个命令?
当前回答
这是一种检索body“AND”状态代码并将其格式化为适当的json或任何适合您的格式的方法。有些人可能会认为这是写格式选项的不正确使用,但这对我来说是有效的,当我需要在我的脚本中的主体和状态代码来检查状态代码并从服务器中继回响应。
curl -X GET -w "%{stderr}{\"status\": \"%{http_code}\", \"body\":\"%{stdout}\"}" -s -o - “https://github.com” 2>&1
运行上面的代码,你应该得到一个json格式:
{
"status" : <status code>,
"body" : <body of response>
}
使用-w write format选项,因为stderr是先打印的,你可以用var http_code格式化你的输出,并将响应的主体放在一个值(body)中,然后使用var stdout跟随封闭。然后将stderr输出重定向到stdout,您将能够将http_code和响应体结合到一个整洁的输出中
其他回答
详细模式会告诉你一切
curl -v http://localhost
一个清晰的使用管道读取
function cg(){
curl -I --silent www.google.com | head -n 1 | awk -F' ' '{print $2}'
}
cg
# 200
欢迎在这里使用我的dotfile脚本
解释
——silent:使用管道时不显示进度条 head -n 1:只显示第一行 -F' ':使用分隔符分隔文本 '{print $2}':显示第二列
我使用这个命令打印状态代码,而不输出任何其他结果。此外,它将只执行HEAD请求并遵循重定向(分别为-I和-L)。
curl -o -I -L -s -w "%{http_code}" http://localhost
这使得检查运行状况脚本中的状态代码非常容易:
sh -c '[ $(curl -o -I -L -s -w "%{http_code}" http://localhost) -eq 200 ]'
我发现这个问题是因为我想要独立访问响应和内容,以便为用户添加一些错误处理。
Curl允许您自定义输出。您可以打印HTTP状态代码以std输出并将内容写入另一个文件。
curl -s -o response.txt -w "%{http_code}" http://example.com
这允许您检查返回代码,然后决定是否值得打印、处理、记录响应等。
http_response=$(curl -s -o response.txt -w "%{http_code}" http://example.com)
if [ $http_response != "200" ]; then
# handle error
else
echo "Server returned:"
cat response.txt
fi
%{http_code}是一个由curl代替的变量。你可以做更多的事情,或者发送代码到stderr,等等。参见curl手册和——write-out选项。
-w, --write-out Make curl display information on stdout after a completed transfer. The format is a string that may contain plain text mixed with any number of variables. The format can be specified as a literal "string", or you can have curl read the format from a file with "@filename" and to tell curl to read the format from stdin you write "@-". The variables present in the output format will be substituted by the value or text that curl thinks fit, as described below. All variables are specified as %{variable_name} and to output a normal % you just write them as %%. You can output a newline by using \n, a carriage return with \r and a tab space with \t. The output will be written to standard output, but this can be switched to standard error by using %{stderr}.
https://man7.org/linux/man-pages/man1/curl.1.html
根据我的经验,我们通常这样使用旋度
curl -f http://localhost:1234/foo || exit 1
curl: (22) The requested URL returned error: 400 Bad Request
这样我们就可以在curl失败时使用管道,并且它还显示状态代码。