반응형

HTTP 요청을 보내고 응답을 받아 보자.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
using System.Net.Http;
 
namespace ConsoleApp1
{
    class Program
    {
        // HttpClient is intended to be instantiated once per application, rather than per-use.
        static readonly HttpClient httpClient = new HttpClient();
 
        static async Task Main(string[] args)
        {
            try
            {
                Console.Write("Enter URI: ");
                string uriString = Console.ReadLine();
 
                HttpResponseMessage httpResponseMessage = await httpClient.GetAsync(uriString.Trim());
                httpResponseMessage.EnsureSuccessStatusCode();
                // Throws an exception if the IsSuccessStatusCode property for the HTTP response is false.
                string responseBody = await httpResponseMessage.Content.ReadAsStringAsync();
                // Above three lines can be replaced with new helper method below
                //string responseBody = await httpClient.GetStringAsync(uriString.Trim());
 
                Console.WriteLine(responseBody);
            }
            catch (HttpRequestException e)
            {
                Console.WriteLine(e.Message);
            }
        }
    }
}
 

 

소스를 입력하고 빌드한다.

 

원하는 URI를 입력하면 데이터가 출력된다.

 

반응형
Posted by J-sean
: