Advanced usage of Fetch
Fetch
不僅能夠抓取普通網頁或資料,也能支援使用 HTTP POST
、DELETE
方法。
Table of Contents
- HTTP POST
- Form Data
- HTTP DELETE
- Error Handler
- Status Code
- Send (Upload) Files
- Custom Headers
- Fetch With Raw Data
- More
HTTP POST
以下範例將示範使用 Fetch.post
抓取 http://httpbin.org/post
並夾帶 test=123
的資料
示範:
{
"json": {
"test": "123"
},
"origin": "127.0.0.1",
"url": "http://httpbin.org/post"
}
首先設計資料模型物件
示範:
public class DataModel
{
public string url { get; set; }
public string origin { get; set; }
public ArgsModel json { get; set; }
}
public class ArgsModel
{
public string test { get; set; }
}
準備要放在 Body 中傳送的資料
示範:
var data = new
{
test = "123"
};
或者你可以傳送 Dictionary
物件
示範:
Dictionary<string, string> data = new Dictionary<string, string>();
data.Add("test", "123");
只能是
Dictionary<string, string>
不可為其他型態
使用 HTTP POST 將資料取回並填充到指定物件
示範:
Fetch f = new Fetch("http://httpbin.org/post");
DataModel response = f.post<DataModel>(data);
Console.WriteLine(response.url);
Console.WriteLine(response.origin);
Console.WriteLine(response.json.test);
輸出:
http://httpbin.org/get?test=123
127.0.0.1
123
Form Data
Fetch 預設會以 json 編碼傳送資料,如果需要傳統的 From 編碼格式,可以在 contentType
中指定
Fetch f = new Fetch("https://httpbin.org/post");
// 預設
f.contentType = "application/json";
// 使用 URL 編碼傳送資料 x-www-form-urlencoded
f.contentType = "application/x-www-form-urlencoded";
// 使用傳統 Form 傳送資料
f.contentType = "multipart/form-data"
HTTP DELETE
用法與 HTTP POST 完全相同,只需要將呼叫改為 Fetch.delete
示範:
Fetch f = new Fetch("http://httpbin.org/delete");
var data = new
{
test = "123"
};
DataModel response = f.delete<DataModel>(data);
請注意,
Fetch.post
與Fetch.delete
預設使用Content-Type: application/json
將資料傳換成 JSON 格式後傳送,如果您需要其他格式可以參閱 Custom Request Data 章節。
Error Handler
Fetch
提供簡便的錯誤控制,任何 Response 的 HTTP Status Code 如果不是 200 OK
,則 Fetch.get
、Fetch.post
與Fetch.delete
均會以 null
回傳。
若需要取得錯誤的 Response 可以使用 Fetch.getResponse()
示範:
Fetch fetch = new Fetch("http://httpbin.org/get");
var data = new
{
test = "123"
};
string response = fetch.delete(data);
// Fetch 請求失敗 (不是 200 OK)
if(response==null)
Console.WriteLine(fetch.getResponse());
由於 http://httpbin.org/get
不能進行 HTTP DELETE 呼叫,所以會回傳 405 Method Not Allowed,
輸出:
<!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>
Status Code
送出請求後,可以取出最後的 Status Code 進行後續判斷
示範:
Fetch fetch = new Fetch("http://httpbin.org/get");
string response = fetch.delete(null);
// 取出最終 Status code
int statusCode = fetch.getStatusCode();
Send (Upload) Files
Fetch.post
提供非常簡便的檔案傳送(上傳)的方法,以下範例示範如何傳送(上傳)檔案
示範:
Fetch fetch = new Fetch("http://httpbin.org/post");
// 表單資料
var form = new
{
test = "123"
};
// 檔案資料 f(名稱): path(檔案路徑)
var files = new
{
f1 = @"C:\Users\user\Pictures\stickers\1.png",
f2 = @"C:\Users\user\Pictures\stickers\2.png"
};
// fetch.post(表單資料,queryString,檔案資料)
string response = fetch.post(form,null,files);
Console.WriteLine(response);
傳送(上傳)檔案時,請確保您對該檔案與目錄都有足夠的存取權限
‼️ 選定送出的檔案路徑後,Fetch.post
就會自動將檔案內容讀取,並依照 W3C 規範的 multipart/form-data
格式
送出的資料:
Content-Type: multipart/form-data; boundary=AaB03x
--AaB03x
Content-Disposition: form-data; name="test"
123
--AaB03x
Content-Disposition: form-data; name="files"
Content-Type: multipart/mixed; boundary=BbC04y
--BbC04y
Content-Disposition: file; filename="1.png"
Content-Type: image/png
Content-Transfer-Encoding: binary
... contents of 1.png ...
--BbC04y
Content-Disposition: file; filename="2.png"
Content-Type: image/png
Content-Transfer-Encoding: binary
...contents of 2.png...
--BbC04y--
--AaB03x--
Custom Headers
可以自訂 Header 資訊,支援匿名物件與 Dictionary 物件
示範:
Fetch fetch = new Fetch("http://httpbin.org/get");
// 自訂 User Agent
fetch.userAgent = "Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36";
// 自訂夾帶的 Header
fetch.header = new
{
test = 123
};
// 如果 Header 的 key 有特殊字元,可以改用 Dictionary<string,string>
fetch.header = new Dictionary<string, string>() {
{ "test", "123" }
};
Set Cookies
以下方式可以簡易設定,將 Cookie 附加在 Request 中
Fetch f = new Fetch("https://httpbin.org/cookies");
f.header = new {
cookie = "aaa=123"
};
Fetch With Raw Data
如果需要傳送指定編碼格式的資料請求,例如:傳統的 Web Service 走的是 SOAP 連線協定,資料傳送以 XML 格式為主
示範呼叫 Web Service + 傳送 (上傳) 檔案:
// 某個 WebService 要求格式
string data = @"<?xml version=""1.0"" encoding =""utf-8"" ?>
<soap:Envelope xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns:soap=""http://schemas.xmlsoap.org/soap/envelope/"">
<soap:Body>
<SaveDocument xmlns=""http://tempuri.org/"">
<docbinaryarray>{0}</docbinaryarray>
<docname>{1}</docname>
</SaveDocument>
</soap:Body>
</soap:Envelope>";
// 讀取檔案
byte[] bytes = File.ReadAllBytes(@"C:\Users\user\123.png");
// 將檔案轉以 Base64 編碼
string file = Convert.ToBase64String(bytes);
// 呼叫 WebService
Fetch f = new Fetch("http://localhost:64199/WebService.asmx");
// 將 Contnet-Type 改為 text/xml
f.contentType = "text/xml; charset=utf-8";
// 將 XML 以原始資料傳送 (不做任何處理)
f.isRaw = true;
// 自訂 Header
f.header = new
{
SOAPAction = "http://tempuri.org/SaveDocument"
};
// 將資料填寫到要求的格式中
data = string.Format(data, file, "123.png");
// 傳送請求
string res = f.post(data);
上面僅用 Web Service 作為示範,您也可以用在其他需要傳送特殊編碼或是原始資料的地方,使用自定義的資料進行請求。