■ HttpClient 클래스의 PostAsJsonAsync/GetFromJsonAsync/GetAsync/PutAsJsonAsync/DeleteAsync 메소드를 사용해 REST API를 호출하는 방법을 보여준다.
※ REST API 서버는 파이썬 서버를 사용했다 : https://icodebroker.com/archives/107331
▶ TodoItem.cs
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 |
using System.Text.Json.Serialization; namespace TestProject; /// <summary> /// 할일 항목 /// </summary> public class TodoItem { //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region ID - ID /// <summary> /// ID /// </summary> [JsonPropertyName("id")] public int ID { get; set; } #endregion #region 항목 - Item /// <summary> /// 항목 /// </summary> [JsonPropertyName("item")] public string Item { get; set; } #endregion } |
▶ UpdateTodoItem.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
using System.Text.Json.Serialization; namespace TestProject; /// <summary> /// 업데이트 할일 항목 /// </summary> public class UpdateTodoItem { //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 항목 - Item /// <summary> /// 항목 /// </summary> [JsonPropertyName("item")] public string Item { get; set; } #endregion } |
▶ Todo.cs
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 |
using System.Collections.Generic; using System.Text.Json.Serialization; namespace TestProject; /// <summary> /// 할일 /// </summary> public class Todo { //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 할일 항목 리스트 - TodoItemList /// <summary> /// 할일 항목 리스트 /// </summary> [JsonPropertyName("todoItemList")] public List<TodoItem> TodoItemList { get; set; } #endregion } |
▶ RESTClient.cs
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 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 |
using System; using System.Collections.Generic; using System.IO; using System.Net.Http; using System.Net.Http.Json; using System.Text.Json; using System.Threading.Tasks; namespace TestProject; /// <summary> /// REST 클라이언트 /// </summary> public class RESTClient : IDisposable { //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// 리소스 해제 여부 /// </summary> private bool disposed = false; /// <summary> /// 기본 URL /// </summary> private string baseURL; /// <summary> /// HTTP 클라이언트 /// </summary> private HttpClient client; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 기본 URL - BaseURL /// <summary> /// 기본 URL /// </summary> public string BaseURL { get { return this.baseURL; } } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Consturctor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - RESTClient(baseURL) /// <summary> /// 생성자 /// </summary> /// <param name="baseURL">기본 URL</param> /// <remarks> /// baseURL은 예를 들어서 http://127.0.0.1:8000으로 설정한다. /// http://127.0.0.1:8000/으로 설정하면 오류가 발생할 수 있다. /// </remarks> public RESTClient(string baseURL) { this.baseURL = baseURL; this.client = new HttpClient { BaseAddress = new Uri(baseURL) }; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Destructor #region 소멸자 - ~RESTClient() /// <summary> /// 소멸자 /// </summary> ~RESTClient() { Dispose(); } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Public #region POST 요청하기 (비동기) - PostAsync<TItem, TResponse>(url, source) /// <summary> /// POST 요청하기 (비동기) /// </summary> /// <typeparam name="TItem">항목 타입</typeparam> /// <typeparam name="TResponse">응답 타입</typeparam> /// <param name="relativeURL">상대적 URL</param> /// <param name="item">항목</param> /// <returns>응답 태스크</returns> public async Task<TResponse> PostAsync<TItem, TResponse>(string relativeURL, TItem item) { HttpResponseMessage responseMessage = await this.client.PostAsJsonAsync(relativeURL, item); responseMessage.EnsureSuccessStatusCode(); TResponse response = await responseMessage.Content.ReadFromJsonAsync<TResponse>(); if(response != null) { return response; } else { throw new ArgumentNullException(nameof(response)); } } #endregion #region GET 요청하기 (비동기) - GetAsync<TResponse>(relativeURL) /// <summary> /// GET 요청하기 (비동기) /// </summary> /// <typeparam name="TResponse">응답 타입</typeparam> /// <param name="relativeURL">상대적 URL</param> /// <returns>응답 태스크</returns> public async Task<TResponse> GetAsync<TResponse>(string relativeURL) { TResponse response = await this.client.GetFromJsonAsync<TResponse>(relativeURL); if(response != null) { return response; } else { throw new ArgumentNullException(nameof(response)); } } #endregion #region GET STREAM 요청하기 (비동기) - GetStreamAsync<TItem>(relativeURL) /// <summary> /// GET STREAM 요청하기 (비동기) /// </summary> /// <typeparam name="TItem">항목 타입</typeparam> /// <param name="relativeURL">상대적 URL</param> /// <returns>항목 비동기 열거 가능형 인터페이스</returns> public async IAsyncEnumerable<TItem> GetStreamAsync<TItem>(string relativeURL) { HttpResponseMessage httpResponseMessage = await this.client.GetAsync(relativeURL, HttpCompletionOption.ResponseHeadersRead); httpResponseMessage.EnsureSuccessStatusCode(); using Stream stream = await httpResponseMessage.Content.ReadAsStreamAsync(); using StreamReader streamReader = new StreamReader(stream); string line; while((line = await streamReader.ReadLineAsync()) != null) { if(!string.IsNullOrWhiteSpace(line)) { TItem item = JsonSerializer.Deserialize<TItem>(line); if(item != null) { yield return item; } } } } #endregion #region PUT 요청하기 (비동기) - PutAsync<TItem, TResponse>(relativeURL, item) /// <summary> /// PUT 요청하기 (비동기) /// </summary> /// <typeparam name="TItem">항목 타입</typeparam> /// <typeparam name="TResponse">응답 타입</typeparam> /// <param name="relativeURL">상대적 URL</param> /// <param name="item">항목</param> /// <returns>응답 태스크</returns> public async Task<TResponse> PutAsync<TItem, TResponse>(string relativeURL, TItem item) { HttpResponseMessage responseMessage = await this.client.PutAsJsonAsync(relativeURL, item); responseMessage.EnsureSuccessStatusCode(); TResponse response = await responseMessage.Content.ReadFromJsonAsync<TResponse>(); if(response != null) { return response; } else { throw new ArgumentNullException(nameof(response)); } } #endregion #region DELETE 요청하기 (비동기) - DeleteAsync<TResponse>(relativeURL) /// <summary> /// DELETE 요청하기 (비동기) /// </summary> /// <typeparam name="TResponse">응답 타입</typeparam> /// <param name="relativeURL">상대적 URL</param> /// <returns>응답 태스크</returns> public async Task<TResponse> DeleteAsync<TResponse>(string relativeURL) { HttpResponseMessage responseMessage = await this.client.DeleteAsync(relativeURL); responseMessage.EnsureSuccessStatusCode(); TResponse response = await responseMessage.Content.ReadFromJsonAsync<TResponse>(); if(response != null) { return response; } else { throw new ArgumentNullException(nameof(response)); } } #endregion #region 리소스 해제하기 - Dispose() /// <summary> /// 리소스 해제하기 /// </summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } #endregion ////////////////////////////////////////////////////////////////////////////////////////// Protected #region 리소스 해제하기 - Dispose(disposing) /// <summary> /// 리소스 해제하기 /// </summary> /// <param name="disposing">리소스 해제 여부</param> protected virtual void Dispose(bool disposing) { if(!this.disposed) { if(disposing) { if(this.client != null) { this.client.Dispose(); this.client = null; } this.disposed = true; } } } #endregion } |
▶ Program.cs
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 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 |
using System; using System.Collections.Generic; using System.Threading.Tasks; namespace TestProject; /// <summary> /// 프로그램 /// </summary> class Program { //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Private #region GET HOME 요청하기 (비동기) - GetHomeAsync(client) /// <summary> /// GET HOME 요청하기 (비동기) /// </summary> /// <param name="client">REST 클라이언트</param> /// <returns>태스크</returns> private static async Task GetHomeAsync(RESTClient client) { string relativeURL = "/home"; Dictionary<string, string> responseDictionary = await client.GetAsync<Dictionary<string, string>>(relativeURL); Console.WriteLine($"GET {client.BaseURL}{relativeURL}"); Console.WriteLine($" {responseDictionary["message"]}"); Console.WriteLine(); } #endregion #region GET ITEMS 요청하기 (비동기) - GetItemsAsync(client) /// <summary> /// GET ITEMS 요청하기 (비동기) /// </summary> /// <param name="client">REST 클라이언트</param> /// <returns>태스크</returns> private static async Task GetItemsAsync(RESTClient client) { string relatveURL = "/todo"; Todo responseTodo = await client.GetAsync<Todo>(relatveURL); Console.WriteLine($"GET ITEMS {client.BaseURL}{relatveURL}"); Console.WriteLine($" {responseTodo.TodoItemList.Count}"); foreach(TodoItem todoItem in responseTodo.TodoItemList) { Console.WriteLine($" ID : {todoItem.ID}, ITEM : {todoItem.Item}"); } Console.WriteLine(); } #endregion #region GET ITEM 요청하기 - GetItemAsync(client) /// <summary> /// GET ITEM 요청하기 /// </summary> /// <param name="client">REST 클라이언트</param> /// <returns>태스크</returns> private static async Task GetItemAsync(RESTClient client) { string relativeURL = "/todo/3"; Dictionary<string, TodoItem> responseDictionary = await client.GetAsync<Dictionary<string, TodoItem>>(relativeURL); Console.WriteLine($"GET {client.BaseURL}{relativeURL}"); Console.WriteLine($" {responseDictionary["todoItem"].Item}"); Console.WriteLine(); } #endregion #region POST ITEMS 요청하기 (비동기) - PostItemsAsync(client) /// <summary> /// POST ITEMS 요청하기 (비동기) /// </summary> /// <param name="client">REST 클라이언트</param> /// <returns>태스크</returns> private static async Task PostItemsAsync(RESTClient client) { string relativeURL = "/todo"; for(int i = 1; i <= 5; i++) { TodoItem todoItem = new TodoItem { ID = i, Item = DateTime.Now.ToString() }; Dictionary<string, string> responseDictionary = await client.PostAsync<TodoItem, Dictionary<string, string>>(relativeURL, todoItem); Console.WriteLine($"POST {client.BaseURL}{relativeURL}"); Console.WriteLine($" {responseDictionary["message"]}"); Console.WriteLine(); } } #endregion #region PUT ITEM 요청하기 (비동기) - PutItemAsync(client) /// <summary> /// PUT ITEM 요청하기 (비동기) /// </summary> /// <param name="client">REST 클라이언트</param> /// <returns>태스크</returns> private static async Task PutItemAsync(RESTClient client) { UpdateTodoItem updateTodoItem = new UpdateTodoItem { Item = DateTime.Now.ToString() }; string relativeURL = "/todo/3"; Dictionary<string, string> responseDictionary = await client.PutAsync<UpdateTodoItem, Dictionary<string, string>>(relativeURL, updateTodoItem); Console.WriteLine($"PUT ITEM {client.BaseURL}{relativeURL}"); Console.WriteLine($" {responseDictionary["message"]}"); Console.WriteLine(); } #endregion #region DELETE ITEMS 요청하기 (비동기) - DeleteItemsAsync(client) /// <summary> /// DELETE ITEMS 요청하기 (비동기) /// </summary> /// <param name="client">REST 클라이언트</param> /// <returns>태스크</returns> private static async Task DeleteItemsAsync(RESTClient client) { string relativeURL = "/todo"; Dictionary<string, string> responseDictionary = await client.DeleteAsync<Dictionary<string, string>>(relativeURL); Console.WriteLine($"DELETE ITEMS {client.BaseURL}{relativeURL}"); Console.WriteLine($" {responseDictionary["message"]}"); Console.WriteLine(); } #endregion #region DELETE ITEM 요청하기 (비동기) - DeleteItemAsync(client) /// <summary> /// DELETE ITEM 요청하기 (비동기) /// </summary> /// <param name="client">REST 클라이언트</param> /// <returns>태스크</returns> private static async Task DeleteItemAsync(RESTClient client) { string relativeURL = "/todo/5"; Dictionary<string, string> responseDictionary = await client.DeleteAsync<Dictionary<string, string>>(relativeURL); Console.WriteLine($"DELETE ITEM {client.BaseURL}{relativeURL}"); Console.WriteLine($" {responseDictionary["message"]}"); Console.WriteLine(); } #endregion #region ENUMERATE ITEMS 요청하기 (비동기) - EnumerateItemsAsync(client) /// <summary> /// ENUMERATE ITEMS 요청하기 (비동기) /// </summary> /// <param name="client">REST 클라이언트</param> /// <returns>태스크</returns> private static async Task EnumerateItemsAsync(RESTClient client) { string relatveURL = "/todos"; IAsyncEnumerable<TodoItem> responseEnumerable = client.GetStreamAsync<TodoItem>(relatveURL); Console.WriteLine($"ENUMERATE ITEMS {client.BaseURL}{relatveURL}"); await foreach(TodoItem todoItem in responseEnumerable) { Console.WriteLine($" ID : {todoItem.ID}, ITEM {todoItem.Item}"); } Console.WriteLine(); } #endregion #region 프로그램 시작하기 - Main() /// <summary> /// 프로그램 시작하기 /// </summary> /// <returns>태스크</returns> static async Task Main() { string baseURL = "http://127.0.0.1:8000"; RESTClient client = new RESTClient(baseURL); await GetHomeAsync(client); await GetItemsAsync(client); await DeleteItemsAsync(client); await PostItemsAsync(client); await GetItemsAsync(client); await GetItemAsync(client); await Task.Delay(1000); await PutItemAsync(client); await GetItemsAsync(client); await DeleteItemAsync(client); await EnumerateItemsAsync(client); } #endregion } |