使用 shell 解析 HTTP 响应

使用 shell 解析 HTTP 响应

我想解析下面的 HTTP 响应,但我无法弄清楚如何使用单个curl 请求单独 grep 值。

我需要这两个输出。 1. status_code - (HTTP 状态代码数组) 2. exceptionMsg - (变量中发生的异常)

 HTTP/1.1 100 Continue

    HTTP/1.1 400 Bad Request
    Content-Type: application/json; charset=utf-8
    Content-Length: 173
    Connection: close

    {"RemoteException":{"exception":"IllegalArgumentException","javaClassName":"java.lang.IllegalArgumentException","message":"Failed to parse \"false?op=CREATE\" to Boolean."}}

我试过这个

curl -i  -X PUT -T test1.txt "http request"| grep HTPP
curl -i  -X PUT -T test1.txt "http request" | grep Exception

我怎样才能用一个命令完成这个任务?

答案1

grep支持正则表达式。例子:

curl -i  -X PUT -T test1.txt "http request"|  grep -E "(HTTP|Exception)"

答案2

您可以尝试将curl 输出保存到临时文件,获取状态代码,然后删除文件。

...
# put response in a temporary file
curl -i http://www.example.com -o response.html

# initialise array to hold status_codes in
status_codes=()

status_codes+=$(sed -n "1p" response.html | grep -o "[[:digit:]]\{3\}")
status_codes+=($(sed -n "3p" response.html | grep -o "[[:digit:]]\{3\}"))
#                       ^ change this to the line numnber where the reponse code is

# print status_codes array (you probably want to comment this out)
declare -p status_codes

rm response.html

相关内容