-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHttpUtils.cs
More file actions
157 lines (135 loc) · 5.14 KB
/
HttpUtils.cs
File metadata and controls
157 lines (135 loc) · 5.14 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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
using System;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;
using Object = UnityEngine.Object;
namespace NeoModLoader.AutoUpdate;
/// <summary>
/// This class is made as utility to make http request easier. Maybe not, just for myself --inmny.
/// </summary>
public static class HttpUtils
{
private static LoadingScreen loading_screen;
public static async Task DownloadFile(string url, string file_path)
{
var client = new HttpClient();
using HttpResponseMessage response = client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead)
.ConfigureAwait(false)
.GetAwaiter().GetResult();
try
{
response.EnsureSuccessStatusCode();
}
catch (HttpRequestException e)
{
return;
}
HttpContent content = response.Content;
if (content == null) throw new Exception("No content in response");
HttpContentHeaders headers = content.Headers;
var content_length = headers.ContentLength;
using var response_stream = content.ReadAsStreamAsync();
var dir = Path.GetDirectoryName(file_path);
if (!Directory.Exists(dir)) Directory.CreateDirectory(dir);
using var file_stream = new FileStream(file_path, FileMode.Create);
var buffer = new byte[4096];
int bytesRead;
ulong total_bytes = 0;
ulong received_bytes = 0;
if (headers.ContentLength.HasValue) total_bytes = (ulong)content_length.Value;
log_progress(received_bytes, total_bytes);
var last_time = DateTime.Now.Second;
while (true)
{
bytesRead = await response_stream.Result.ReadAsync(buffer, 0, buffer.Length);
var now = DateTime.Now.Second;
if (bytesRead == 0)
{
if (now - last_time > 3) break;
continue;
}
await file_stream.WriteAsync(buffer, 0, bytesRead);
received_bytes += (ulong)bytesRead;
now = DateTime.Now.Second;
if (now != last_time)
{
log_progress(received_bytes, total_bytes);
last_time = now;
}
}
void log_progress(ulong received, ulong total)
{
if (loading_screen == null)
{
loading_screen = Object.FindObjectOfType<LoadingScreen>();
if (loading_screen == null) Debug.Log("Failed to find loading screen.");
}
var msg = $"Downloading latest {Path.GetFileName(file_path)}: {received}/{total} bytes";
if (LocalizedTextManager.instance.language == "cz" || LocalizedTextManager.instance.language == "ch")
msg = $"正在下载最新 {Path.GetFileName(file_path)}: {received}/{total} B";
if (loading_screen != null)
{
loading_screen.loadingHelperText.text = msg;
Debug.Log(msg);
}
if (loading_screen?.inGameScreen ?? false) WorldTip.showNow(msg, false, "top");
}
}
public static string Request(string url, string param = "", string method = "get")
{
ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072; //TLS1.2=3702
string result = "";
HttpWebRequest req = WebRequest.Create(url) as HttpWebRequest;
if (req == null) return result;
req.Method = method;
req.ContentType = @"application/octet-stream";
req.UserAgent =
@"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36";
byte[] post_data = Encoding.GetEncoding("UTF-8").GetBytes(param);
HttpWebResponse res;
if (post_data.Length > 0)
{
req.ContentLength = post_data.Length;
req.Timeout = 15000;
Stream output_stream = req.GetRequestStream();
output_stream.WriteAsync(post_data, 0, post_data.Length);
output_stream.FlushAsync();
output_stream.Close();
try
{
res = (HttpWebResponse)req.GetResponse();
Stream input_stream = res.GetResponseStream();
Encoding encoding = Encoding.GetEncoding("UTF-8");
StreamReader sr = new(input_stream, encoding);
result = sr.ReadToEnd();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return result;
}
}
else
{
try
{
res = (HttpWebResponse)req.GetResponse();
Stream input_stream = res.GetResponseStream();
Encoding encoding = Encoding.GetEncoding("UTF-8");
StreamReader sr = new(input_stream, encoding);
result = sr.ReadToEnd();
sr.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return result;
}
}
return result;
}
}