Fetch

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

Configuration

使用 Fetch 之前,可以依照需求在 app.configweb.config 中添加以下設定

<appSettings>
    <add key="Storage" value="D:\Storage"/>
    <add key="Proxy" value="192.168.1.1:8888"/>
</appSettings>
  • storage 為可選項目,會自動任何發送紀錄、回應、程式錯誤...等訊息自動記錄到該目錄中

  • Proxy 為可選項目,如果網路請求需要先經過 Proxy,請給予正確的 Proxy 設定。反之則不需要設定。

Super simple to use

以下範例將示範抓取 https://www.youtube.com/results?search_query=柴犬 的 HTML 頁面原始碼

範例:

Fetch f = new Fetch("https://www.youtube.com/results");
var query = new
{
    search_query = "柴犬"
};

string html = f.get(query);
Console.WriteLine(html); // 輸出

輸出:

 <!DOCTYPE html>
 <html lang="zh-TW" data-cast-api-enabled="true">
 <head>
     <style name="www-roboto" >.
         @font-face{
             font-family:'Roboto';
             font-style:italic;
             font-weight:400;
             src:local('Roboto Italic'),local('Robot
...

Deserialize JSON

Fetch 物件使用 Json.NET 強大的對應機制,可以將回覆的資料自動幫您填充到指定的物件中

以下範例將抓取 http://httpbin.org/get?test=123 所回傳的 JSON 資料,並填充到指定的物件中

回應的資料:

{
  "args": {
    "test": "123"
  },
  "origin": "122.146.90.216",
  "url": "http://httpbin.org/get?test=123"
}

首先設計資料模型 (Model) 物件:

public class DataModel
{
    public string url { get; set; }
    public string origin { get; set; }
    public ArgsModel args { get; set; }
}

public class ArgsModel
{
    public string test { get; set; }
}

抓取資料並自動對應到模型 (Model):

Fetch f = new Fetch("http://httpbin.org/get");
var query = new
{
    test = "123"
};

DataModel data = f.get<DataModel>(query);

Console.WriteLine(data.url);
Console.WriteLine(data.origin);
Console.WriteLine(data.args.test);

輸出:

http://httpbin.org/get?test=123
111.111.111.111
123

Download File

您可以用以下簡單的語法,抓取任何網路資源,以下示範如何下載一張圖片:

Fetch f = new Fetch("https://static-s.aa-cdn.net/img/ios/1034197315/6294a01ff5937e26ca7539bea819db52");
byte[] bytes = f.getBinary(null);
if(bytes != null)
    File.WriteAllBytes(@"D:\Image\dog.png",bytes);

More

results matching ""

    No results matching ""