[英]Perl/ curl How to get Status Code and Response Body
我正在嘗試編寫一個簡單的 perl 腳本來調用和 API,如果狀態代碼是 2xx,則對響應執行一些操作。 而如果是 4xx 或 5xx 則執行其他操作。
我遇到的問題是我能夠獲取響應代碼(使用自定義寫出格式化程序並將輸出傳遞到其他地方),或者我可以獲得整個響應和標題。
my $curlResponseCode = `curl -s -o /dev/null -w "%{http_code}" ....`;
只會給我狀態碼。
my $curlResponse = `curl -si ...`;
會給我整個標題加上響應。
我的問題是如何以一種簡潔的格式從服務器獲取響應正文和 http 狀態代碼,使我可以將它們分成兩個單獨的變量。
不幸的是,我不能使用 LWP 或任何其他單獨的庫。
提前致謝。 -斯賓塞
我想出了這個解決方案:
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
...會給我整個標題加上回復。
...以一種簡潔的格式,允許我將它們分成兩個獨立的變量。
由於標題和正文僅由空行分隔,因此您可以拆分此行上的內容:
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;
非常基本 - 您正在捕獲系統命令的輸出。 通過使用為其構建的庫( LWP
來做到這一點遠比這更好。 雖然失敗了 - curl -v
會產生狀態代碼和內容,你將不得不解析它。
您可能還會發現SuperUser上的這個主題非常有用:
https://superuser.com/questions/272265/getting-curl-to-output-http-status-code
特別
#creates a new file descriptor 3 that redirects to 1 (STDOUT)
exec 3>&1
# Run curl in a separate command, capturing output of -w "%{http_code}" into HTTP_STATUS
# and sending the content to this command's STDOUT with -o >(cat >&3)
HTTP_STATUS=$(curl -w "%{http_code}" -o >(cat >&3) 'http://example.com')
(這不是perl,但你可以使用類似的東西。至少,運行-w
並將你的內容捕獲到臨時文件。
還沒有想出一個“純”的Perl
解決方案,但我起草了這個片段來通過curl
檢查頁面的 HTTP 響應代碼:
#!/usr/bin/perl
use v5.30;
use warnings;
use diagnostics;
our $url = "";
my $username = "";
my $password = "";
=begin url_check
Exit if HTTP response code not 200.
=cut
sub url_check {
print "Checking URL status code...\n";
my $status_code =
(`curl --max-time 2.5 --user ${username}:${password} --output /dev/null --silent --head --write-out '%{http_code}\n' $url`);
if ($status_code != '200'){
{
print "URL not accessible. Exiting. \n";
exit;
}
} else {
print "URL accessible. Continuing... \n";
}
}
url_check
curl
的詳細使用或多或少是文檔本身。 我的示例允許您將憑據傳遞給頁面,但可以根據需要將其刪除。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.