Fetch - Basic Usage

Fetch API 的靈感來自 JavaScript,它就像瀏覽器中的 AJAX 功能一樣,提供您方便地進行 HTTP Request 網路存取

Namespace

using ZapLib;

HTTP GET

使用 Fetch 抓取一個 YouTube 搜尋結果的 HTML 原始碼

// 目標網址
Fetch f = new Fetch("https://www.youtube.com/results");

// Query String
var qs = new
{
    search_query = "柴犬"
};

// 發出請求
string result = f.Get(qs);
Console.WriteLine(result);

輸出:

<!DOCTYPE html><html lang="zh-Hant-TW" data-cast-api-enabled="true"><head>
<style name="www-roboto" >
@font-face{font-family:'Roboto';font-style:normal;font-weight:500;src:local
('Roboto Medium'),local('Roboto-Medium'),
url(//fonts.gstatic.com/s/roboto/v18/KFOlCnqEu92Fr1MmEU9fBBc9.ttf)
format('truetype');
...

TLS 1.2 HTTPS

如果 Fetch 的網址是 HTTPS,需要先指定開啟 TLS 1.2

ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;

參考文章:Windows 停用 TLS 1.0 之配套作業整理

Download Resource

下載資源,以一張圖片為例

Fetch f = new Fetch("https://static-s.aa-cdn.net/img/ios/1034197315/6294a01ff5937e26ca7539bea819db52");

// 取得圖片檔案
byte[] img = f.GetBinary();

// 儲存成實體檔案
File.WriteAllBytes("dog.jpg", img);

Fallback

所有請求失敗 (非 200 OK) 的回應,一律回傳 null ,可取得 HTTP Status Code 與失敗的 Response 細節

Fetch f = new Fetch("https://httpbin.org/patch");
string result = f.Get();
// 判斷請求失敗
if (result == null) 
    Console.WriteLine("失敗: " + f.StatusCode + " 原因: " + f.GetResponse());
else 
    Console.WriteLine(result);

輸出:

失敗: 405 原因: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>405 Method Not Allowed</title>
<h1>Method Not Allowed</h1>
<p>The method is not allowed for the requested URL.</p>

Last updated

Was this helpful?