如何使用 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
}

更新時間:2020 年 9 月 25 日

5K+ 瀏覽量

開啟您的 職業生涯

完成課程取得認證

入門
廣告
© . All rights reserved.