Release 12.0.0.18314
[platform/core/csapi/tizenfx.git] / src / Tizen.AIAvatar / src / internal / Common / RestClient.cs
1 /*
2  * Copyright(c) 2024 Samsung Electronics Co., Ltd.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  *
16  */
17
18 using System;
19 using System.Net.Http.Headers;
20 using System.Net.Http;
21 using System.Text;
22 using System.Threading.Tasks;
23 using System.ComponentModel;
24
25 namespace Tizen.AIAvatar
26 {
27     internal class RestClient : IRestClient, IDisposable
28     {
29         private readonly HttpClient client;
30
31         internal RestClient(HttpClient httpClient)
32         {
33             client = httpClient;
34         }
35
36         [EditorBrowsable(EditorBrowsableState.Never)]
37         public async Task<string> SendRequestAsync(HttpMethod method, string endpoint, string bearerToken = null, string jsonData = null)
38         {
39             AddBearerToken(bearerToken);
40
41             HttpRequestMessage request = new HttpRequestMessage(method, endpoint);
42
43             if (jsonData != null)
44             {
45                 request.Content = new StringContent(jsonData, Encoding.UTF8, "application/json");
46             }
47
48             HttpResponseMessage response = await client.SendAsync(request);
49             request?.Dispose();
50             return await HandleResponse(response);
51         }
52
53         [EditorBrowsable(EditorBrowsableState.Never)]
54         public void Dispose()
55         {
56             client.Dispose();
57         }
58
59         private void AddBearerToken(string bearerToken)
60         {
61             if (!string.IsNullOrEmpty(bearerToken))
62             {
63                 client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", bearerToken);
64             }
65         }
66
67         private async Task<string> HandleResponse(HttpResponseMessage response)
68         {
69             if (response.IsSuccessStatusCode)
70             {
71                 return await response.Content.ReadAsStringAsync();
72             }
73             else
74             {
75                 throw new HttpRequestException($"HTTP request failed with status code {response.StatusCode}");
76             }
77         }
78     }
79 }