-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHttpSingleton.cs
More file actions
96 lines (88 loc) · 2.73 KB
/
Copy pathHttpSingleton.cs
File metadata and controls
96 lines (88 loc) · 2.73 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
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
namespace BoughtItems
{
internal class HttpSingleton
{
public HttpSingleton()
{
}
private static HttpClient _client;
public static HttpClient Client
{
get
{
if (_client == null)
{
HttpClientHandler handler = new()
{
CookieContainer = Cookies,
UseCookies = false,
SslProtocols = System.Security.Authentication.SslProtocols.Tls12 | System.Security.Authentication.SslProtocols.Tls13
};
_client = new HttpClient(handler)
{
//Timeout = TimeSpan.FromSeconds(30),
};
}
return _client;
}
}
private static CookieContainer _cookies;
public static CookieContainer Cookies
{
get
{
_cookies ??= new CookieContainer();
return _cookies;
}
}
public static void SetCustomCookie(string domain, string cookiesString)
{
var list = cookiesString.Split(';').Select(i => i.Split('='));
Dictionary<string, string> dictCookies = new();
foreach (var pair in list)
{
string key = pair[0].Trim();
if (key.Length > 0)
{
string value = pair.Length > 1 ? pair[1].Trim() : "";
if (value.Length > 0)
{
dictCookies[key] = value;
}
}
}
List<string> listBaseUrls = new();
if (!domain.StartsWith("http"))
{
//add both http and https
listBaseUrls.Add("http://" + domain);
listBaseUrls.Add("https://" + domain);
}
else
{
listBaseUrls.Add(domain);
}
foreach (var url in listBaseUrls)
{
var uriCookie = new Uri(url);
foreach (var pair in dictCookies)
{
Cookies.Add(uriCookie, new System.Net.Cookie(pair.Key, pair.Value));
}
}
}
public static void SetUserAgent(string userAgent)
{
Client.DefaultRequestHeaders.TryAddWithoutValidation("User-Agent", userAgent);
}
}
}