我正在尝试编写一个简单的perl脚本调用和API,如果状态代码是2xx,则对响应做一些事情.如果它是4xx或5xx,那么做其他事情.
我遇到的问题是我能够获得响应代码(使用自定义写出格式化程序并将输出传递到其他地方)或者我可以得到整个响应和标题.
my $curlResponseCode = `curl -s -o /dev/null -w "%{http_code}" ....`;
只会给我状态代码.
my $curlResponse = `curl -si ...`; 
会给我整个标题加上回复.
我的问题是如何从服务器获取响应主体和http状态代码以一种简洁的格式,允许我将它们分成两个独立的变量.
不幸的是,我不能使用LWP或任何其他单独的库.
提前致谢.-Spencer
max*_*nes 10
我想出了这个解决方案:
URL="http://google.com"
# store the whole response with the status at the and
HTTP_RESPONSE=$(curl --silent --write-out "HTTPSTATUS:%{http_code}" -X POST $URL)
# extract the body
HTTP_BODY=$(echo $HTTP_RESPONSE | sed -e 's/HTTPSTATUS\:.*//g')
# extract the status
HTTP_STATUS=$(echo $HTTP_RESPONSE | tr -d '\n' | sed -e 's/.*HTTPSTATUS://')
# print the body
echo "$HTTP_BODY"
# example using the status
if [ ! $HTTP_STATUS -eq 200  ]; then
  echo "Error [HTTP status: $HTTP_STATUS]"
  exit 1
fi
...会给我整个标题加上响应。
...以一种简洁的格式,允许我将它们分成两个单独的变量。
由于 header 和 body 只是由一个空行分隔,你可以在这一行拆分内容:
 my ($head,$body) = split( m{\r?\n\r?\n}, `curl -si http://example.com `,2 );
并从标题中获取状态代码
 my ($code) = $head =~m{\A\S+ (\d+)};
您也可以将其与正则表达式组合成单个表达式,尽管这可能更难理解:
my ($code,$body) = `curl -si http://example.com` 
      =~m{\A\S+ (\d+) .*?\r?\n\r?\n(.*)}s;
| 归档时间: | 
 | 
| 查看次数: | 7803 次 | 
| 最近记录: |