Repository navigation
Expand file tree
/
Copy pathDetectLanguageHttpClient.cs
More file actions
66 lines (53 loc) · 2.55 KB
/
Copy pathDetectLanguageHttpClient.cs
File metadata and controls
66 lines (53 loc) · 2.55 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
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
namespace DetectLanguage {
public class DetectLanguageHttpClient {
private HttpClient httpClient;
public DetectLanguageHttpClient(DetectLanguageConfiguration configuration) {
httpClient = new HttpClient();
httpClient.BaseAddress = new Uri(configuration.ApiBase);
httpClient.DefaultRequestHeaders.Add("Accept", "application/json");
httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {configuration.ApiKey}");
httpClient.DefaultRequestHeaders.Add("User-Agent", configuration.UserAgent);
}
public async Task<T> GetAsync<T>(string path) {
var response = await httpClient.GetAsync(path);
return await HandleResponse<T>(response);
}
public async Task<T> PostAsync<T>(string path, object request) {
var response = await httpClient.PostAsync(path, BuildContent(request));
return await HandleResponse<T>(response);
}
private static HttpContent BuildContent(object request) {
return new StringContent(
JsonConvert.SerializeObject(request),
Encoding.UTF8,
"application/json");
}
private static async Task<T> HandleResponse<T>(HttpResponseMessage response) {
var content = await response.Content.ReadAsStringAsync();
try {
response.EnsureSuccessStatusCode();
return JsonConvert.DeserializeObject<T>(content);
} catch (HttpRequestException) {
throw BuildException(response, content);
} catch (JsonSerializationException) {
throw BuildInvalidResponseException(response, content);
}
}
private static DetectLanguageException BuildException(HttpResponseMessage response, string content) {
try {
var errorResponse = JsonConvert.DeserializeObject<ErrorResponse>(content);
return new DetectLanguageException(response.StatusCode, errorResponse.error, response);
} catch (JsonSerializationException) {
throw BuildInvalidResponseException(response, content);
}
}
private static DetectLanguageException BuildInvalidResponseException(HttpResponseMessage response, string content) {
return new DetectLanguageException(response.StatusCode, $"Invalid response: {content}", response);
}
}
}