.NET Framework 3.5 使用 WebClient 呼叫 API 範例

在新版本的開發中(.NET Framework 4.5 或以上)建議使用 System.Net.Http.HttpClient 開發,但是我們這次的目標平台是 .NET Framework 3.5。 其他還有 WebAPI 是從 .NET Framework 4.0 版本開始支援。筆者看下來應該是只有 HttpWebRequest, WebClient, WCF(Windows Communication Foundation) 三個可以使用,前兩個是 .NET Framework 1.1 就開始,而後者是從 3.0 開始支援。評估後發現應該是 WebClient 比較容易使用,故選擇 WebClient 最為此次範例。

最簡單 Get 示範

發起 Get 很簡單,最容易忽略的就是設定 Encoding
    
using (var client = new WebClient())
{
    try
    {
        string url = "https://localhost:7041/api/user/2";
        client.Encoding = Encoding.UTF8; // 不指定的話中文會是亂碼

        // 發送 GET 請求並取得回應
        string response = client.DownloadString(url);

        Console.WriteLine(response);
        
        // 不指定 UTF8: {"id":1,"name":"撠?"}
        // 有指定 UTF8: {"id":1,"name":"小明"}
    }
    catch (WebException e)
    {
        Console.WriteLine("API 錯誤: " + e.Message);
    }
}
    

最簡單 Post 示範

UploadData 是將位元組陣列傳送,並取得位元組陣列的回應內容,所以需要先將字串轉換為位元組陣列。這裡比較重要的是需要設定 Content-Type ,常用的有 application/json, application/x-www-form-urlencoded ,並且也不要忘記需要使用 UTF8 編碼。
    
string url = "https://localhost:7041/api/user";

using (var client = new WebClient())
{
    try
    {
        client.Encoding = Encoding.UTF8; // 不指定的話中文會是亂碼
        client.Headers.Add("Content-Type", "application/json"); // 需要手動指定 Content-Type 

        string request = "{\"id\":1,\"name\":\"大頭\"}";
    
        byte[] bytesResult = client.UploadData(url, "POST", Encoding.UTF8.GetBytes(request));

        string result = Encoding.UTF8.GetString(bytesResult);
        Console.WriteLine(result);
    }
    catch (Exception e)
    {
        Console.WriteLine("API 錯誤: " + e.Message);
    }
}
    


註: WebClient 無法設定 timeout,如果 URL 有問題會直接卡住

參考資料:
Microsoft.Learn - WebClient Class
The Will Will Web - 利用 WebClient 類別模擬 HTTP POST 表單送出的注意事項

留言