Fetch - Customized

Fetch 允許你全權控制並決定該怎麼發送 HTTP Request

Call Web Service (SOAP 1.1)

假設有一個 Web Service 提供上傳檔案的功能,要求的格式如下

SOAP 1.1 /Uploading.asmx?op=UploadFiles

POST /Uploading.asmx HTTP/1.1
Host: localhost
Content-Type: text/xml; charset=utf-8
Content-Length: length
SOAPAction: "http://tempuri.org/UploadFiles"

<?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>
    <UploadFiles xmlns="http://tempuri.org/">
      <fs>base64Binary</fs>
      <fileName>string</fileName>
    </UploadFiles>
  </soap:Body>
</soap:Envelope>

Custom Fetch

// SOAP 要求的資料格式
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>
        <UploadFiles xmlns=""http://tempuri.org/"">
          <fs>{0}</fs>
          <fileName>{1}</fileName>
        </UploadFiles>
      </soap:Body>
    </soap:Envelope>";

// 讀取檔案
byte[] bytes = File.ReadAllBytes(Environment.CurrentDirectory + "\\1.png");

// 將檔案轉以 Base64 編碼
string file = Convert.ToBase64String(bytes);

// 將資料設定到指定格式中
data = string.Format(data, file, "1.png");

// 呼叫 WebService
Fetch f = new Fetch("http://localhost:10178/Uploading.asmx");

// 將 Contnet-Type 改為 text/xml, 並指定 Header
f.ContentType = "text/xml";
f.Header = new
{
    SOAPAction = "http://tempuri.org/UploadFiles"
};

// 發送 post 方法
string response = f.Post(data.Trim());

// 取得回傳結果
Console.WriteLine(response);

輸出:

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <soap:Body>
        <UploadFilesResponse xmlns="http://tempuri.org/">
        <UploadFilesResult>上傳成功:1.png Size:40944</UploadFilesResult>
        </UploadFilesResponse>
    </soap:Body>
</soap:Envelope>

Last updated

Was this helpful?