Add Tizen.AIAvatar project (#6014)
[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             return await HandleResponse(response);
50         }
51
52         [EditorBrowsable(EditorBrowsableState.Never)]
53         public void Dispose()
54         {
55             client.Dispose();
56         }
57
58         private void AddBearerToken(string bearerToken)
59         {
60             if (!string.IsNullOrEmpty(bearerToken))
61             {
62                 client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", bearerToken);
63             }
64         }
65
66         private async Task<string> HandleResponse(HttpResponseMessage response)
67         {
68             if (response.IsSuccessStatusCode)
69             {
70                 return await response.Content.ReadAsStringAsync();
71             }
72             else
73             {
74                 throw new HttpRequestException($"HTTP request failed with status code {response.StatusCode}");
75             }
76         }
77     }
78 }