This repository was archived by the owner on Dec 2, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathHttpHelper.cs
More file actions
116 lines (93 loc) · 3.19 KB
/
HttpHelper.cs
File metadata and controls
116 lines (93 loc) · 3.19 KB
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
using AniAPI.NET.Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
namespace AniAPI.NET.Helpers
{
internal class HttpHelper
{
private string _protocol;
private string _hostName;
private string _version;
private string _jwt;
private HttpClient _httpClient;
public HttpHelper()
{
_protocol = "https";
_hostName = "api.aniapi.com";
_version = "v1";
_httpClient = new HttpClient();
}
private string endpoint => $"{_protocol}://{_hostName}/{_version}";
private async Task<APIResponse<T>> executeRequest<T>(string path, HttpMethod method, string body = null, bool auth = false)
{
try
{
string uri = $"{endpoint}/{path}";
HttpRequestMessage request = new HttpRequestMessage(method, uri);
if (auth)
{
request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", _jwt);
}
if (!string.IsNullOrEmpty(body))
{
request.Content = new StringContent(body, Encoding.UTF8, "application/json");
}
HttpResponseMessage response = await _httpClient.SendAsync(request);
if (!response.IsSuccessStatusCode)
{
throw new Exception(response.StatusCode.ToString());
}
string responseContent = await response.Content.ReadAsStringAsync();
APIResponse<T> result = null;
try
{
result = JsonConvert.DeserializeObject<APIResponse<T>>(responseContent);
}
catch
{
JObject error = JObject.Parse(responseContent);
throw new InvalidOperationException(error.Value<string>("data"));
}
if(result.StatusCode != 200)
{
throw new Exception($"{result.StatusCode}: {result.Message}");
}
return result;
}
catch(Exception ex)
{
throw;
}
}
public void UseHTTP()
{
_protocol = "http";
}
public void UseHTTPS()
{
_protocol = "https";
}
public void SetJWT(string jwt)
{
_jwt = jwt;
}
public async Task<APIResponse<T>> UnauthorizedRequest<T>(string path, HttpMethod method)
{
return await executeRequest<T>(path, method);
}
public async Task<APIResponse<T>> AuthorizedRequest<T>(string path, HttpMethod method, string body = null)
{
if (string.IsNullOrEmpty(_jwt))
{
throw new ArgumentException("You need to login to perform this request", "JWT");
}
return await executeRequest<T>(path, method, body, true);
}
}
}