-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWebApiInvoker.cs
More file actions
67 lines (56 loc) · 2.11 KB
/
WebApiInvoker.cs
File metadata and controls
67 lines (56 loc) · 2.11 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
namespace Huawei.DeveloperApi
{
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Olive;
class WebApiInvoker
{
public Encoding Encoding { get; set; } = Encoding.UTF8;
public TimeSpan Timeout { get; set; } = 30.Seconds();
public Task<T> PostJson<T>(string path, object request, string accessToken)
where T : HuaweiResultBase, new()
{
return Send<T>(async (client, enc) =>
{
var accessTokenStr = Convert.ToBase64String(Encoding.UTF8.GetBytes($"APPAT:{accessToken}"));
client.DefaultRequestHeaders.Authorization =
new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", accessTokenStr);
var payload = new StringContent(request.ToJson(), Encoding, "application/json");
return await client.PostAsync(path, payload);
});
}
public Task<T> PostForm<T>(string path, object request)
where T : HuaweiResultBase, new()
{
return Send<T>(async (client, enc) =>
{
var payload = new FormUrlEncodedContent(request.ToDictionary());
return await client.PostAsync(path, payload);
});
}
async Task<T> Send<T>(Func<HttpClient, Encoding, Task<HttpResponseMessage>> requestInitiator) where T : HuaweiResultBase, new()
{
try
{
var client = CreateClient();
var message = await requestInitiator(client, Encoding);
return Encoding.GetString(await message.Content.ReadAsByteArrayAsync()).FromJson<T>();
}
catch (Exception ex)
{
return CreateDefault<T>(ex);
}
}
T CreateDefault<T>(Exception ex) where T : HuaweiResultBase, new() => new()
{
ResponseCode = "unhandled_exception",
ResponseMessage = ex.Message
};
HttpClient CreateClient() => new()
{
Timeout = Timeout
};
}
}