如何在C#中使用WebClient将数据发布到特定的URL?
我们可以使用Web客户端从WebAPI获取和发布数据。Web客户端提供了用于从服务器发送和接收数据的通用方法
Web客户端易于使用以使用WebAPI。您也可以使用httpClient代替WebClient
WebClient类使用WebRequest类提供对资源的访问。
WebClient实例可以使用通过WebRequest.RegisterPrefix方法注册的任何WebRequest后代访问数据。
Namespace:System.Net Assembly:System.Net.WebClient.dll
UploadString将String发送到资源,并返回包含任何响应的String。
示例
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
}