Computer >> 컴퓨터 >  >> 프로그램 작성 >> C#

C#에서 WebClient를 사용하여 특정 URL에 데이터를 게시하는 방법은 무엇입니까?

<시간/>

웹 클라이언트를 사용하여 웹 API에서 데이터를 가져오고 게시할 수 있습니다. 웹 클라이언트는 서버에서 데이터를 보내고 받는 일반적인 방법을 제공합니다.

웹 클라이언트는 Web API를 사용하는 데 사용하기 쉽습니다. WebClient 대신 httpClient를 사용할 수도 있습니다.

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
}