반응형

C# -- HttpClient 기본 사용법



** https, http 모두 상관없이 사용가능함.



** Main() 함수에서는 await 를 사용못함

   --> 따라서, Main() 함수내에서, 비동기함수를 동기적으로 실행시키기위해서는 .GetAwaiter().GetResult() 를 사용해야함.



using System;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;

namespace HttpClient_test
{
    class Program
    {
        static readonly HttpClient httpClient = new HttpClient();

        //static HttpRequestHeaders requestHeaders = httpClient.DefaultRequestHeaders;

        static void Main(string[] args)
        {

            string httpsUrl = "https://jsonplaceholder.typicode.com/todos/1"
            string httpUrl = "http://jsonplaceholder.typicode.com/todos/2";

            Console.WriteLine($" -------- HTTPS ------------");

            Test(httpsUrl).GetAwaiter().GetResult();  // Main함수에서 await Test(httpsUrl) 사용못하므로, 이를 대신함

            Console.WriteLine($"\n\n\n --------- HTTP ------------");

            Test(httpUrl).GetAwaiter().GetResult();

            Console.WriteLine($" ---------- END ------------");
            Console.Read();
        }

        static async Task Test(string url)
        {
            try
            {
                using (var response = await httpClient.GetAsync(url))
                {
                    Console.WriteLine(response.StatusCode);

                    if (HttpStatusCode.OK == response.StatusCode)
                    {
                        string body = await response.Content.ReadAsStringAsync();
                        Console.WriteLine(body);
                    }
                    else
                    {
                        Console.WriteLine($" -- response.ReasonPhrase ==> {response.ReasonPhrase}");
                    }
                }

            }
            catch (HttpRequestException ex)
            {
                Console.WriteLine($"ex.Message={ex.Message}");
                Console.WriteLine($"ex.InnerException.Message = {ex.InnerException.Message}");

                Console.WriteLine($"----------- 서버에 연결할수없습니다 ---------------------");
            }
            catch (Exception ex2)
            {
                Console.WriteLine($"Exception={ex2.Message}");
            }
        }
    }
}




** 실행결과






반응형
Posted by 자유프로그램
,