如何使用 C# 中的 WebClient 将数据发布到特定的 URL?
我们可以使用 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
}
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP