60.1 HttpClient 클래스로 웹 데이터 가져오기

    닷넷에서 제공하는 HttpClient 클래스를 사용하면 인터넷에 연결된 네트워크상의 데이터를 가져오거나 전송할 수 있습니다. 다음 예제는 닷넷 코어 콘솔 프로젝트에서 http://www.microsoft.com 웹 사이트의 HTML 문서를 읽어 콘솔에 출력합니다.

    HTML 문서를 읽어 콘솔에 출력: HttpClientDemo/HttpClientDemo.cs

    using System;
    using System.Net.Http;
    using System.Threading.Tasks;
    
    class HttpClientDemo
    {
        static async Task Main()
        {
            //① HttpClient 개체 생성
            HttpClient httpClient = new HttpClient();
    
            //② GetAsync() 메서드 호출
            HttpResponseMessage httpResponseMessage =
                await httpClient.GetAsync("http://www.microsoft.com/");
    
            //③ HTML 가져오기
            string responseBody = await httpResponseMessage.Content.ReadAsStringAsync();
    
            //④ 출력
            Console.WriteLine(responseBody);
        }
    }

    출력 내용은 때에 따라 다르기에 따로 표현하지 않았습니다. HTML로 내려받은 문자열은 웹 브라우저 같은 프로그램에서는 HTML을 실행해서 보여 주지만, 이 예제에서는 그대로 텍스트로 화면에 출력합니다.

    GetAsync()처럼 해당 URL로 데이터를 전송하는 PostAsync() 메서드도 제공합니다. HttpClient 클래스와 같은 API는 때에 따라 더 향상된 클래스로 추가해서 제공하기도 합니다.

    신간 소식 구독하기
    뉴스레터에 가입하시고 이메일로 신간 소식을 받아 보세요.