HTTP 範圍請求

5 min

language: ja bn en es hi pt ru zh-cn zh-tw

你好,我是無能。
我一直認為,HTTP Get請求每次都會獲取整個頁面,這讓我感覺一點也不環保。
如果最終只需要獲取所需資訊,例如只獲取<head>內的內容,就只獲取一部分;如果不是,就獲取整個頁面並進行提取。
如果能這樣做,網路傳輸成本和解析head內標籤的處理都會對CPU更友善且時間更短,感覺好處多多。
而且,既然是TCP通訊,我想HTTP應該沒有什麼做不到的,一查果然可以。
HTTP 範圍請求

使用 curl 測試

看來可以像這樣,透過-H選項在標頭資訊中附加範圍大小來進行限制。

$ curl -H &quot;Range: bytes=0-1024&quot; https://soulminingrig.com/
&lt;!DOCTYPE html&gt;
&lt;html lang=&quot;ja&quot;&gt;&lt;head&gt;&lt;meta charset=&quot;utf-8&quot;&gt;&lt;meta content=&quot;width=device-width,initial-scale=1.0&quot; name=&quot;viewport&quot;&gt;&lt;title&gt;Home - SOULMINIGRIG&lt;/title&gt;&lt;meta content=&quot;light dark&quot; name=&quot;supported-color-schemes&quot;&gt;&lt;meta content=&quot;hsl(220, 20%, 100%)&quot; media=&quot;(prefers-color-scheme: light)&quot; name=&quot;theme-color&quot;&gt;&lt;meta content=&quot;hsl(220, 20%, 10%)&quot; media=&quot;(prefers-color-scheme: dark)&quot; name=&quot;theme-color&quot;&gt;&lt;link href=&quot;/pagefind/pagefind-ui.css&quot; rel=&quot;stylesheet&quot;&gt;&lt;link href=&quot;/styles.css&quot; rel=&quot;stylesheet&quot;&gt;&lt;link href=&quot;/feed.xml&quot; rel=&quot;alternate&quot; title=&quot;SOULMINIGRIG&quot; type=&quot;application/atom+xml&quot;&gt;&lt;link href=&quot;/feed.json&quot; rel=&quot;alternate&quot; title=&quot;SOULMINIGRIG&quot; type=&quot;application/json&quot;&gt;&lt;link href=&quot;/favicon.png&quot; rel=&quot;icon&quot; sizes=&quot;32x32&quot; type=&quot;image/png&quot;&gt;&lt;link href=&quot;https://soulminingrig.com/&quot; rel=&quot;canonical&quot;&gt;&lt;script src=&quot;/js/main.js&quot; type=&quot;module&quot;&gt;&lt;/script&gt;&lt;style&gt;.page-title{background:var(--color-highlight);padding:.5em;font-size:1.2em}&lt;/style&gt;&lt;script data-website-id=&quot;6031aa47-e715-4f87-a99a-9e3046e5dcdc&quot; defer=&quot;&quot; src=&quot;https://n

因為是範圍指定,所以即使不是從開頭也可以。

$ curl -H &quot;Range: bytes=1025-1025&quot; https://soulminingrig.com/
o

甚至連1位元組也能正確返回。

實用方面

只需在標頭資訊中附加即可設定獲取時的範圍限制,因此基本上任何語言都可以做到,最重要的是,可以實現對網路頻寬的環保使用,這通常不太被意識到。
如果只想提取HTML的<head>內容,可以指定Range: bytes=0-4096,如果不行,就獲取全部,或者如果想更環保,則以4096位元組為單位,在下一個範圍內發送Get請求。
結果是,後續處理的函式庫提取HTML標籤的時間也會縮短,並且對目標伺服器也更友善。

但是,正如MDN網站上所說的
「確認伺服器是否支援部分請求」如果假設現在大多數地方都支援,那就不太好,如果想嚴格執行,就必須使用從標頭資訊返回的判斷條件。

然而,新的網路帝王出現了...

如果使用冠以NET這個彷彿是新網路之王的股票代碼的CloudFlare,由於似乎會按請求單位進行限制,即使處理速度加快,途中若因DDoS防護而被阻擋,最終意義也不會太強烈。
但是,例如在VPS上運行某個Bot時,如果對外部請求佔用大量頻寬(雖然可能沒有人會用到這種程度...),那麼像這次這樣的部分請求可能會有效果。

然而,由於HTTP請求的內容應該會被儲存到記憶體空間中,所以多少會感覺記憶體使用量有所減少,因此如果有人想製作獲取網站資訊的工具,加入這個功能也能讓對方的操作稍微友善一些,所以有必要時可能需要這樣做。

這就是我似乎知道,但實際上卻不經意間不知道的HTTP知識。

Related Posts