如何在 C# 中使用 WebClient 将数据发布到特定 URL?
csharpserver side programmingprogramming更新于 2025/6/26 8:37:17
我们可以使用 Web 客户端从 Web API 获取和发布数据。Web 客户端提供了从服务器发送和接收数据的常用方法。
Web 客户端易于使用,方便使用 Web API。您也可以使用 httpClient 代替 WebClient。
WebClient 类使用 WebRequest 类提供对资源的访问。
WebClient 实例可以使用任何已通过 WebRequest.RegisterPrefix 方法注册的 WebRequest 子类访问数据。
Namespace:System.Net Assembly:System.Net.WebClient.dll
UploadString 向资源发送字符串,并返回包含任何响应的字符串。
示例
class Program{ public static void Main(){ User user = new User(); try{ using (WebClient webClient = new WebClient()){ webClient.BaseAddress = "https://jsonplaceholder.typicode.com"; var url = "/posts"; webClient.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)"); webClient.Headers[HttpRequestHeader.ContentType] ="application/json"; string data = JsonConvert.SerializeObject(user); var response = webClient.UploadString(url, data); var result = JsonConvert.DeserializeObject<object>(response); System.Console.WriteLine(result); } } catch (Exception ex){ throw ex; } } } class User{ public int id { get; set; } = 1; public string title { get; set; } = "First Data"; public string body { get; set; } = "First Body"; public int userId { get; set; } = 222; }
输出
{ "id": 101, "title": "First Data", "body": "First Body", "userId": 222 }