我使用curl来获取http报头以查找http状态代码并返回响应。我使用命令获取http头信息

curl -I http://localhost

为了得到响应,我使用命令

curl http://localhost

一旦使用了-I标志,我就只得到了头信息,响应就不再存在了。是否有一种方法可以同时获得http响应和头/http状态码在一个命令?


当前回答

仅捕获响应: curl——location——请求GET“http://localhost:8000” 捕获响应和它的状态码: curl——location——request GET "http://localhost:8000" -w "%{http_code}" 在文件中捕获响应: curl——location——request GET "http://localhost:8000" -s -o "response.txt"

其他回答

这个命令

 curl http://localhost -w ", %{http_code}"

将得到以逗号分隔的正文和状态;你可以把它们分开取出来。

您可以随心所欲地更改分隔符。

while : ; do curl -sL -w "%{http_code} %{url_effective}\\n" http://host -o /dev/null; done

在末尾追加一行“http_code:200”,然后grep关键字“http_code:”并提取响应代码。

result=$(curl -w "\nhttp_code:%{http_code}" http://localhost)

echo "result: ${result}"   #the curl result with "http_code:" at the end

http_code=$(echo "${result}" | grep 'http_code:' | sed 's/http_code://g') 

echo "HTTP_CODE: ${http_code}"  #the http response code

在这种情况下,您仍然可以使用非静默模式/ verbose模式来获取有关请求的更多信息,例如curl响应体。

我发现这个问题是因为我想要独立访问响应和内容,以便为用户添加一些错误处理。

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文档来得到一个解决方案,该文档指定使用-来将输出输出到stdout。

curl -o - -I http://localhost

要用http返回代码获得响应,我可以这样做

curl -o /dev/null -s -w "%{http_code}\n" http://localhost