C# WebClient 類是一個基于異步編程模型的類,用于從網絡上下載數據或向網絡上上傳數據。以下是 WebClient 類可以實現的一些功能:
下載文件:可以使用 WebClient 類的 DownloadFile 方法從指定的 URL 下載文件并將其保存到本地文件系統中。
WebClient client = new WebClient();
string url = "https://example.com/file.txt";
string filePath = "C:/file.txt";
client.DownloadFile(url, filePath);
上傳文件:可以使用 WebClient 類的 UploadFile 方法將本地文件上傳到指定的 URL。
WebClient client = new WebClient();
string url = "https://example.com/upload";
string filePath = "C:/file.txt";
byte[] fileBytes = File.ReadAllBytes(filePath);
client.UploadFile(url, filePath, fileBytes);
下載字符串:可以使用 WebClient 類的 DownloadString 方法從指定的 URL 下載文本數據并將其作為字符串讀取。
WebClient client = new WebClient();
string url = "https://example.com/text";
string result = client.DownloadString(url);
上傳字符串:可以使用 WebClient 類的 UploadString 方法將字符串數據上傳到指定的 URL。
WebClient client = new WebClient();
string url = "https://example.com/upload";
string data = "Hello, world!";
client.UploadString(url, data);
設置請求頭:可以使用 WebClient 類的方法設置 HTTP 請求頭,例如設置 User-Agent、Cookie 等。
WebClient client = new WebClient();
client.Headers["User-Agent"] = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3";
處理異常:WebClient 類在下載或上傳數據時可能會拋出異常,例如網絡連接錯誤、HTTP 錯誤等??梢允褂?try-catch 語句處理這些異常。
WebClient client = new WebClient();
try
{
string result = client.DownloadString("https://example.com/text");
}
catch (WebException ex)
{
Console.WriteLine("Error: " + ex.Message);
}