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

curl -I http://localhost

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

curl http://localhost

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


当前回答

在末尾追加一行“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响应体。

其他回答

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

我的方法是:

为了获得两者(标题和正文),我通常执行curl - d - <url>,如:

$ curl -D- http://localhost:1234/foo
HTTP/1.1 200 OK
Connection: Keep-Alive
Transfer-Encoding: chunked
Content-Type: application/json
Date: Wed, 29 Jul 2020 20:59:21 GMT

{"data":["out.csv"]}

这将转储标题(- d)到stdout(-)(在man curl中查找——dump-header)。

恕我直言,在这种情况下也很方便:

我经常使用jq来获得json数据(例如从一些其他api)格式化。但是由于jq不需要HTTP标头,诀窍是使用-D/dev/stderr将标头打印到stderr。注意,这次我们还使用-sS(——silent,——show-errors)来抑制进度表(因为我们写入管道)。

$ curl -sSD/dev/stderr http://localhost:1231/foo | jq .
HTTP/1.1 200 OK
Connection: Keep-Alive
Transfer-Encoding: chunked
Content-Type: application/json
Date: Wed, 29 Jul 2020 21:08:22 GMT

{
  "data": [
    "out.csv"
  ]
}

我想这也可以很方便,如果你想打印头部(快速检查)控制台,但重定向主体到一个文件(例如,当它的某种二进制不混乱你的终端):

$ curl -sSD/dev/stderr http://localhost:1231 > /dev/null
HTTP/1.1 200 OK
Connection: Keep-Alive
Transfer-Encoding: chunked
Content-Type: application/json
Date: Wed, 29 Jul 2020 21:20:02 GMT

注意:这与curl -I <url>!As -I将执行HEAD请求而不是GET请求(在man curl中查找——HEAD。是:对于大多数HTTP服务器,这将产生相同的结果。但是我知道很多商业应用程序根本没有实现HEAD请求;-P

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

curl -o - -I http://localhost

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

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

在末尾追加一行“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响应体。