-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHttpClientController.cs
More file actions
77 lines (73 loc) · 2.55 KB
/
HttpClientController.cs
File metadata and controls
77 lines (73 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
67
68
69
70
71
72
73
74
75
76
77
using System.Globalization;
using System.Net;
namespace Hardstuck.Http
{
/// <summary>
/// Modified HttpClient class with extra methods and setups.
/// </summary>
public class HttpClientController : HttpClient
{
#region definitions
/// <summary>
/// The version of the HttpClientController.
/// </summary>
public static float Version => 1.02f;
/// <summary>
/// Create an instance of HttpClientController, child of HttpClient.
/// </summary>
public HttpClientController()
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
DefaultRequestHeaders.UserAgent.Add(new System.Net.Http.Headers.ProductInfoHeaderValue("HsClientController", Version.ToString("0.00", CultureInfo.InvariantCulture)));
}
#endregion
/// <summary>
/// Downloads a file asynchronously.
/// </summary>
/// <param name="url">URL to download from.</param>
/// <param name="destination">Destination to download to.</param>
/// <returns>Boolean whether the file was downloaded successfully.</returns>
public async Task<bool> DownloadFileAsync(string url, string destination)
{
try
{
var uri = new Uri(url);
using var responseMessage = await GetAsync(uri);
if (!responseMessage.IsSuccessStatusCode)
{
return false;
}
using var response = await responseMessage.Content.ReadAsStreamAsync();
using var stream = File.Create(@destination);
await response.CopyToAsync(stream);
return true;
}
catch
{
return false;
}
}
/// <summary>
/// Downloads a file to a string asynchronously.
/// </summary>
/// <param name="url">URL to download from.</param>
/// <returns>The response as a string.</returns>
public async Task<string?> DownloadFileToStringAsync(string url)
{
try
{
var uri = new Uri(url);
using var responseMessage = await GetAsync(uri);
if (!responseMessage.IsSuccessStatusCode)
{
return null;
}
return await responseMessage.Content.ReadAsStringAsync();
}
catch
{
return null;
}
}
}
}