|
1 |
using System.Diagnostics;
|
|
2 |
using System.Net.Http.Json;
|
|
3 |
using System.Text.Json;
|
|
4 |
using System.Text.Json.Serialization;
|
|
5 |
using LDClient.network.data;
|
|
6 |
using Newtonsoft.Json;
|
|
7 |
using Newtonsoft.Json.Linq;
|
|
8 |
|
|
9 |
namespace LDClient.network {
|
|
10 |
public class ApiClient : IApiClient {
|
|
11 |
|
|
12 |
public static readonly Payload ExampleInfo = new() {
|
|
13 |
UserName = "honikCz",
|
|
14 |
HostName = "Bramborak",
|
|
15 |
TimeStamp = DateTime.Parse("2022-03-21 18:05:00.168895"),
|
|
16 |
HeadDevice = new DebuggerInfo {
|
|
17 |
SerialNumber = "C12345678912"
|
|
18 |
},
|
|
19 |
BodyDevice = new DebuggerInfo {
|
|
20 |
SerialNumber = "C98765432198"
|
|
21 |
},
|
|
22 |
Status = ConnectionStatus.Connected
|
|
23 |
};
|
|
24 |
|
|
25 |
|
|
26 |
private readonly string _uri;
|
|
27 |
private readonly HttpClient _client;
|
|
28 |
private readonly uint _retryPeriod;
|
|
29 |
|
|
30 |
|
|
31 |
public ApiClient(string url, uint port, string path, uint retryPeriod) {
|
|
32 |
_uri = $"{url}:{port}{path}";
|
|
33 |
_retryPeriod = retryPeriod;
|
|
34 |
|
|
35 |
_client = new HttpClient();
|
|
36 |
|
|
37 |
}
|
|
38 |
|
|
39 |
public async Task SendPayloadAsync(Payload payload) {
|
|
40 |
try {
|
|
41 |
Stopwatch stopWatch = new();
|
|
42 |
stopWatch.Start();
|
|
43 |
|
|
44 |
var json = JsonConvert.SerializeObject(ExampleInfo);
|
|
45 |
if (json is null) {
|
|
46 |
Program.DefaultLogger.Error($"Failed to serialize object: {ExampleInfo}");
|
|
47 |
return;
|
|
48 |
}
|
|
49 |
var response = await _client.PostAsJsonAsync(_uri, payload, new JsonSerializerOptions {
|
|
50 |
Converters = {
|
|
51 |
new JsonStringEnumConverter( JsonNamingPolicy.CamelCase)
|
|
52 |
}
|
|
53 |
|
|
54 |
});
|
|
55 |
stopWatch.Stop();
|
|
56 |
Response2Log(json, response, stopWatch.ElapsedMilliseconds);
|
|
57 |
|
|
58 |
response.EnsureSuccessStatusCode();
|
|
59 |
var serverResponse = await response.Content.ReadAsStringAsync();
|
|
60 |
CheckResponse(serverResponse);
|
|
61 |
} catch (Exception e) {
|
|
62 |
Program.DefaultLogger.Error($"Failed to send {payload} to the server. Due to: {e.Message}");
|
|
63 |
}
|
|
64 |
}
|
|
65 |
|
|
66 |
private static bool CheckResponse(string response) {
|
|
67 |
dynamic json = JObject.Parse(response);
|
|
68 |
|
|
69 |
if (json.statusCode < 400) {
|
|
70 |
return true;
|
|
71 |
}
|
|
72 |
throw new Exception($"Server responded with error code: {json.statusCode}");
|
|
73 |
}
|
|
74 |
}
|
|
75 |
}
|
re #9438 Added API client + example data