using System;
using System.Net;
class Program
{
static void Main()
{
// 创建一个 WebClient 实例
using (WebClient client = new WebClient())
{
try
{
// 下载字符串内容
string url = "http://example.com";
string content = client.DownloadString(url);
Console.WriteLine("下载的内容: ");
Console.WriteLine(content);
// 上传数据示例
string uploadUrl = "http://example.com/upload";
string data = "key1=value1&key2=value2";
byte[] responseBytes = client.UploadData(uploadUrl, "POST", System.Text.Encoding.UTF8.GetBytes(data));
string response = System.Text.Encoding.UTF8.GetString(responseBytes);
Console.WriteLine("上传的响应: ");
Console.WriteLine(response);
}
catch (WebException ex)
{
Console.WriteLine("发生错误: " + ex.Message);
}
}
}
}
创建 WebClient 实例:
using 语句确保 WebClient 对象在使用完毕后自动释放资源。下载字符串内容:
DownloadString 方法从指定的 URL 下载字符串内容,并将其打印到控制台。上传数据:
UploadData 方法将数据以 POST 请求的方式上传到指定的 URL。异常处理:
try-catch 块捕获可能发生的网络异常,并输出错误信息。上一篇:c# findwindow
下一篇:c#版本
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站