chr
2024-09-04 d7be195b0e1949c7b38bce2ad83ae974cbfac094
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
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;
using System.Reflection;
using System.Web;
using System.IO;
using log4net.Plugin;
using PdmSwPlugin.Common.Setting;
 
namespace AutoUpdater.Util
{
    public static class HttpUtil
    {
        private static readonly string ApiKey = "X-Access-Token";
        public static readonly string BASE_CLIENT_NAME = "BaseClient";
        private static IHttpClientFactory ClientFactory;
 
        [Obsolete]
        private static string DownloadDir;
        public static void Init()
        {
            ServiceProvider ser = new ServiceCollection().AddHttpClient(BASE_CLIENT_NAME, c =>
            {
                c.BaseAddress = new Uri(PluginSetting.Instance.BaseAddress);
                c.Timeout = TimeSpan.FromSeconds(PluginSetting.Instance.TimeOut);
                c.DefaultRequestHeaders
                .Add(ApiKey,
                    "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2Nzg5NjI5NzgsInVzZXJuYW1lIjoiY2hlbmhhb3JhbiJ9.Ir8u0j5mRsmi-QGtAsYP-cZxlRjnYBDf7sNoHf3uWQs");
            })
              .Services
              .BuildServiceProvider();
            ClientFactory = ser.GetService<IHttpClientFactory>();
        }
 
        public static HttpClient GetClient()
        {
            return ClientFactory.CreateClient(BASE_CLIENT_NAME);
        }
 
        public static HttpClient GetClient(string clientName)
        {
            return ClientFactory.CreateClient(clientName);
        }
 
 
        public static Result<T> GetSyncAction<T>(this HttpClient client, string url, params object[] models)
        {
            return JsonUtil.Deserialize<Result<T>>(GetSyncAction(client, url, models));
        }
 
        public static string GetSyncAction(this HttpClient client, string url, params object[] models)
        {
            foreach (object model in models)
            {
                url = url.ModelToUriParam(model);
            }
 
            Task<string> task = client.GetStringAsync(url);
            task.Wait();
            return task.Result;
 
        }
        public static async Task<T> GetAsyncAction<T>(this HttpClient client, string url, params object[] models)
        {
            foreach (object model in models)
            {
                url = url.ModelToUriParam(model);
            }
            return JsonUtil.Deserialize<T>(await client.GetStringAsync(url));
        }
 
        public static T PostSyncAction<T>(this HttpClient client, string url, string data)
        {
            StringContent content = new StringContent(data, Encoding.UTF8, "application/json");
            Task<HttpResponseMessage> task = client.PostAsync(url, content);
            task.Wait();
            HttpResponseMessage response = task.Result;
            response.EnsureSuccessStatusCode();
            Task<string> task2 = response.Content.ReadAsStringAsync();
            task2.Wait();
            string responseBody = task2.Result;
            return JsonUtil.Deserialize<T>(responseBody);
        }
 
        public static Result<T> PostSyncAction<T>(this HttpClient client, object data, string url)
        {
            string dataStr = JsonUtil.Serialize(data);
            StringContent content = new StringContent(dataStr, Encoding.UTF8, "application/json");
            Task<HttpResponseMessage> task = client.PostAsync(url, content);
            task.Wait();
            HttpResponseMessage response = task.Result;
            response.EnsureSuccessStatusCode();
            Task<string> task2 = response.Content.ReadAsStringAsync();
            task2.Wait();
            string responseBody = task2.Result;
            return JsonUtil.Deserialize<Result<T>>(responseBody);
        }
 
        public static string PostSyncAction(this HttpClient client, string url, string data)
        {
            StringContent content = new StringContent(data, Encoding.UTF8, "application/json");
            Task<HttpResponseMessage> task = client.PostAsync(url, content);
            task.Wait();
            HttpResponseMessage response = task.Result;
            response.EnsureSuccessStatusCode();
            Task<string> task2 = response.Content.ReadAsStringAsync();
            task2.Wait();
            return task2.Result;
        }
 
        public static async Task<T> PostAsyncAction<T>(this HttpClient client, string url, string data)
        {
            StringContent content = new StringContent(data, Encoding.UTF8, "application/json");
            HttpResponseMessage response = await client.PostAsync(url, content);
            _ = response.EnsureSuccessStatusCode();
            return JsonUtil.Deserialize<T>(await response.Content.ReadAsStringAsync());
        }
 
        public static async Task<T> PostAsyncAction<T>(this HttpClient client, string url, object data)
        {
            string dataStr = JsonUtil.Serialize(data);
            StringContent content = new StringContent(dataStr, Encoding.UTF8, "application/json");
            HttpResponseMessage response = await client.PostAsync(url, content);
            _ = response.EnsureSuccessStatusCode();
            return JsonUtil.Deserialize<T>(await response.Content.ReadAsStringAsync());
        }
 
        public static async Task<string> GetDownload(this HttpClient client, string url, string dir, string fileName, params object[] models)
        {
            foreach (object model in models)
            {
                url = url.ModelToUriParam(model);
            }
            HttpResponseMessage response = await client.GetAsync(url);
            // 服务器返回的文件名
            string originFileName = HttpUtility.UrlDecode(response.Headers.GetValues("FileName").FirstOrDefault());
            string fullPath;
            using (Stream stream = await response.Content.ReadAsStreamAsync())
            {
                // 拼接一个新的本地文件名
                string suffix = Path.GetExtension(originFileName);
                string newFileName = Path.GetFileNameWithoutExtension(fileName) + suffix;
                fullPath = $"{dir}/{newFileName}";
                using (FileStream fs = new FileStream(fullPath, FileMode.Create))
                {
                    byte[] buffer = new byte[1024];
                    int readLength = 0;
                    int length;
                    while ((length = await stream.ReadAsync(buffer, 0, buffer.Length)) != 0)
                    {
                        readLength += length;
                        fs.Write(buffer, 0, length);
                    }
                }
            }
            return fullPath;
        }
 
        public static async void GetDownloadWithName(this HttpClient client, string url, params object[] models)
        {
            foreach (object model in models)
            {
                url = url.ModelToUriParam(model);
            }
 
            string dir = DownloadDir;
            HttpResponseMessage response = await client.GetAsync(url);
            string fileName = HttpUtility.UrlDecode(response.Headers.GetValues("FileName").FirstOrDefault());
            using (Stream stream = await response.Content.ReadAsStreamAsync())
            {
                // string suffix = Path.GetExtension(response.RequestMessage.RequestUri.ToString());
                string suffix = Path.GetExtension(fileName);
                using (FileStream fs = new FileStream($"{dir}/{fileName}", FileMode.CreateNew))
                {
                    byte[] buffer = new byte[1024];
                    int readLength = 0;
                    int length;
                    while ((length = await stream.ReadAsync(buffer, 0, buffer.Length)) != 0)
                    {
                        readLength += length;
                        fs.Write(buffer, 0, length);
                    }
                }
 
            }
        }
 
        public static string ModelToUriParam(this string url, object obj)
        {
            PropertyInfo[] properties = obj.GetType().GetProperties();
            StringBuilder sb = new StringBuilder()
                .Append(url).Append("?");
            if (obj is Dictionary<string, string>)
            {
                Dictionary<string, string> dict = (Dictionary<string, string>)obj;
                foreach (var item in dict)
                {
                    if (item.Value == null || string.IsNullOrWhiteSpace(item.Value))
                    {
                        continue;
                    }
                    sb = sb.Append(item.Key)
                       .Append("=")
                       .Append(HttpUtility.UrlEncode(item.Value))
                       .Append("&");
                }
            }
            else
            {
                foreach (PropertyInfo p in properties)
                {
                    object v = p.GetValue(obj, null);
                    if (v == null || string.IsNullOrWhiteSpace(v.ToString()))
                    {
                        continue;
                    }
                    sb = sb.Append(p.Name)
                        .Append("=")
                        .Append(HttpUtility.UrlEncode(v.ToString()))
                        .Append("&");
                }
            }
            sb = sb.Remove(sb.Length - 1, 1);
            return sb.ToString();
        }
    }
}