mirror of
https://github.com/modernw/App-Installer-For-Windows-8.x-Reset.git
synced 2026-06-14 03:16:38 +10:00
Update reader.
This commit is contained in:
@@ -46,6 +46,7 @@
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<Compile Include="Download.cs" />
|
||||
<Compile Include="Enumerable.cs" />
|
||||
<Compile Include="HResult.cs" />
|
||||
<Compile Include="IE.cs" />
|
||||
<Compile Include="Locale.cs" />
|
||||
@@ -61,6 +62,7 @@
|
||||
<Compile Include="Utils.cs" />
|
||||
<Compile Include="Version.cs" />
|
||||
<Compile Include="VisualElements.cs" />
|
||||
<Compile Include="Web.cs" />
|
||||
<Compile Include="WebBrowser.cs" />
|
||||
<Compile Include="Window.cs" />
|
||||
</ItemGroup>
|
||||
|
||||
@@ -0,0 +1,159 @@
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Text;
|
||||
|
||||
namespace DataUtils
|
||||
{
|
||||
[ComVisible (true)]
|
||||
[InterfaceType (ComInterfaceType.InterfaceIsDual)]
|
||||
public interface _I_Enumerable
|
||||
{
|
||||
int Length { get; set; }
|
||||
object this [int index] { get; set; }
|
||||
void Add (object value); // push
|
||||
void Push (object value);
|
||||
object Pop (); // 删除并返回末尾元素
|
||||
object Shift (); // 删除并返回开头元素
|
||||
void Unshift (object value); // 在开头插入
|
||||
void RemoveAt (int index); // 删除任意索引
|
||||
void Clear (); // 清空数组
|
||||
_I_Enumerable Slice (int start, int end); // 返回子数组
|
||||
void Splice (int start, int deleteCount, object [] items); // 删除并插入
|
||||
int IndexOf (object value); // 查找索引
|
||||
bool Includes (object value); // 是否包含
|
||||
void ForEach (object callback, bool suppressExceptions = false); // 遍历,callback(item, index)
|
||||
_I_Enumerable Concat (_I_Enumerable other); // 拼接
|
||||
string Join (string separator); // 转字符串
|
||||
object GetItem (int index); // 返回 { key, data } 或直接 data
|
||||
void SetAt (int index, object value); // 替换元素
|
||||
int IndexOfKey (int key); // 按内部 key 查找
|
||||
void Move (int index, int newIndex); // 移动元素
|
||||
void PushAll (object [] items); // 一次性 push 多个
|
||||
}
|
||||
public class _I_List: _I_Enumerable, IList
|
||||
{
|
||||
public _I_List (IEnumerable<object> initArr, bool readOnly = false, bool fixedSize = false, bool sync = true)
|
||||
{
|
||||
_list = initArr?.ToList () ?? new List<object> ();
|
||||
IsFixedSize = fixedSize;
|
||||
IsReadOnly = readOnly;
|
||||
IsSynchronized = sync;
|
||||
}
|
||||
protected List<object> _list;
|
||||
protected object _lock = new object ();
|
||||
public object this [int index] { get { return _list [index]; } set { _list [index] = value; } }
|
||||
public int Count => _list.Count;
|
||||
public bool IsFixedSize { get; }
|
||||
public bool IsReadOnly { get; }
|
||||
public bool IsSynchronized { get; }
|
||||
public int Length
|
||||
{
|
||||
get { return _list.Count; }
|
||||
set
|
||||
{
|
||||
if (!IsFixedSize && !IsReadOnly)
|
||||
{
|
||||
_list.Capacity = value;
|
||||
}
|
||||
}
|
||||
}
|
||||
public object SyncRoot => _lock;
|
||||
public void Add (object value) => _list.Add (value);
|
||||
public void Push (object value) => _list.Add (value);
|
||||
public void RemoveAt (int index) => _list.RemoveAt (index);
|
||||
public void Clear () => _list.Clear ();
|
||||
public int IndexOf (object value) => _list.IndexOf (value);
|
||||
int IList.Add (object value)
|
||||
{
|
||||
_list.Add (value);
|
||||
return _list.Count - 1;
|
||||
}
|
||||
public bool Contains (object value) => _list.Contains (value);
|
||||
public void Insert (int index, object value) => _list.Insert (index, value);
|
||||
public void Remove (object value) => _list.Remove (value);
|
||||
public void ForEach (object callback, bool suppressExceptions = false)
|
||||
{
|
||||
for (int i = 0; i < _list.Count; i++)
|
||||
{
|
||||
var item = _list [i];
|
||||
if (suppressExceptions)
|
||||
{
|
||||
try { JsUtils.Call (callback, item, i); } catch { }
|
||||
}
|
||||
else JsUtils.Call (callback, item, i);
|
||||
}
|
||||
}
|
||||
public IEnumerator GetEnumerator () => _list.GetEnumerator ();
|
||||
public _I_Enumerable Slice (int start, int end)
|
||||
{
|
||||
if (end < 0) end = _list.Count + end;
|
||||
start = Math.Max (0, start);
|
||||
end = Math.Min (_list.Count, end);
|
||||
var arr = _list.GetRange (start, Math.Max (0, end - start));
|
||||
return new _I_List (arr);
|
||||
}
|
||||
public void Splice (int start, int deleteCount, object [] items)
|
||||
{
|
||||
if (start < 0) start = Math.Max (0, _list.Count + start);
|
||||
int count = Math.Min (deleteCount, _list.Count - start);
|
||||
_list.RemoveRange (start, count);
|
||||
if (items != null && items.Length > 0)
|
||||
_list.InsertRange (start, items);
|
||||
}
|
||||
public bool Includes (object value) => _list.Contains (value);
|
||||
public _I_Enumerable Concat (_I_Enumerable other)
|
||||
{
|
||||
var newList = new List<object> (_list);
|
||||
if (other is _I_List)
|
||||
newList.AddRange ((other as _I_List)._list);
|
||||
return new _I_List (newList);
|
||||
}
|
||||
public string Join (string separator)
|
||||
{
|
||||
return string.Join (separator ?? ",", _list.Select (x => x?.ToString () ?? ""));
|
||||
}
|
||||
public object GetItem (int index) => _list [index];
|
||||
public void SetAt (int index, object value) => _list [index] = value;
|
||||
public int IndexOfKey (int key)
|
||||
{
|
||||
return key >= 0 && key < _list.Count ? key : -1;
|
||||
}
|
||||
public void Move (int index, int newIndex)
|
||||
{
|
||||
if (index < 0 || index >= _list.Count || newIndex < 0 || newIndex >= _list.Count) return;
|
||||
var item = _list [index];
|
||||
_list.RemoveAt (index);
|
||||
_list.Insert (newIndex, item);
|
||||
}
|
||||
public void PushAll (object [] items)
|
||||
{
|
||||
if (items == null || items.Length == 0) return;
|
||||
_list.AddRange (items);
|
||||
}
|
||||
public void CopyTo (Array array, int index)
|
||||
{
|
||||
if (array == null) throw new ArgumentNullException (nameof (array));
|
||||
for (int i = 0; i < _list.Count && index + i < array.Length; i++)
|
||||
array.SetValue (_list [i], index + i);
|
||||
}
|
||||
public object Pop ()
|
||||
{
|
||||
if (_list.Count == 0) return null;
|
||||
var last = _list [_list.Count - 1];
|
||||
_list.RemoveAt (_list.Count - 1);
|
||||
return last;
|
||||
}
|
||||
public object Shift ()
|
||||
{
|
||||
if (_list.Count == 0) return null;
|
||||
var first = _list [0];
|
||||
_list.RemoveAt (0);
|
||||
return first;
|
||||
}
|
||||
public void Unshift (object value) => _list.Insert (0, value);
|
||||
}
|
||||
}
|
||||
@@ -131,6 +131,8 @@ namespace DataUtils
|
||||
[ClassInterface (ClassInterfaceType.AutoDual)]
|
||||
public class _I_Process
|
||||
{
|
||||
public Process Start (string filename, string args) => Process.Start (filename, args);
|
||||
public Process Open (string url) => Process.Start (url);
|
||||
public int Run (
|
||||
string cmdline,
|
||||
string filepath,
|
||||
|
||||
@@ -2,7 +2,11 @@
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using System.Xml;
|
||||
using Newtonsoft.Json;
|
||||
|
||||
@@ -186,4 +190,194 @@ namespace DataUtils
|
||||
object BuildJSON ();
|
||||
}
|
||||
}
|
||||
public static class JsUtils
|
||||
{
|
||||
/// <summary>
|
||||
/// 调用 JS 函数。第一个参数作为 this,其余作为 JS 函数参数。
|
||||
/// </summary>
|
||||
/// <param name="callback">JS 函数对象</param>
|
||||
/// <param name="args">JS 函数参数,可选</param>
|
||||
/// <returns>JS 函数返回值</returns>
|
||||
public static void Call (object jsFunc, params object [] args)
|
||||
{
|
||||
if (jsFunc == null) return;
|
||||
object [] invokeArgs = new object [(args?.Length ?? 0) + 1];
|
||||
invokeArgs [0] = jsFunc; // this
|
||||
if (args != null)
|
||||
for (int i = 0; i < args.Length; i++)
|
||||
invokeArgs [i + 1] = args [i];
|
||||
jsFunc.GetType ().InvokeMember (
|
||||
"call",
|
||||
BindingFlags.InvokeMethod,
|
||||
null,
|
||||
jsFunc,
|
||||
invokeArgs);
|
||||
}
|
||||
}
|
||||
[ComVisible (true)]
|
||||
[InterfaceType (ComInterfaceType.InterfaceIsDual)]
|
||||
public interface _I_IAsyncAction
|
||||
{
|
||||
_I_IAsyncAction Then (object resolve, object reject = null, object progress = null);
|
||||
void Done (object resolve, object reject = null);
|
||||
void Catch (object reject);
|
||||
bool IsCompleted { get; }
|
||||
bool IsCancelled { get; }
|
||||
bool IsError { get; }
|
||||
void Cancel ();
|
||||
void ReportProgress (object progress);
|
||||
object Error { get; }
|
||||
}
|
||||
[ComVisible (true)]
|
||||
[ClassInterface (ClassInterfaceType.AutoDual)]
|
||||
public class _I_Task: _I_IAsyncAction
|
||||
{
|
||||
private object _result;
|
||||
private Exception _error;
|
||||
private bool _completed;
|
||||
private bool _cancelled;
|
||||
private List<object> _resolveCallbacks = new List<object> ();
|
||||
private List<object> _rejectCallbacks = new List<object> ();
|
||||
private List<object> _progressCallbacks = new List<object> ();
|
||||
private CancellationTokenSource _cts = new CancellationTokenSource ();
|
||||
public _I_Task (Func<object> func)
|
||||
{
|
||||
ThreadPool.QueueUserWorkItem (_ => {
|
||||
try
|
||||
{
|
||||
if (_cts.Token.IsCancellationRequested)
|
||||
{
|
||||
_cancelled = true;
|
||||
return;
|
||||
}
|
||||
|
||||
_result = func ();
|
||||
_completed = true;
|
||||
|
||||
foreach (var cb in _resolveCallbacks)
|
||||
JsUtils.Call (cb, _result);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_error = ex;
|
||||
foreach (var cb in _rejectCallbacks)
|
||||
JsUtils.Call (cb, ex);
|
||||
}
|
||||
});
|
||||
}
|
||||
public _I_IAsyncAction Then (object resolve, object reject = null, object progress = null)
|
||||
{
|
||||
if (resolve != null) _resolveCallbacks.Add (resolve);
|
||||
if (reject != null) _rejectCallbacks.Add (reject);
|
||||
if (progress != null) _progressCallbacks.Add (progress);
|
||||
return this;
|
||||
}
|
||||
public void Done (object resolve, object reject = null)
|
||||
{
|
||||
if (resolve != null) _resolveCallbacks.Add (resolve);
|
||||
if (reject != null) _rejectCallbacks.Add (reject);
|
||||
}
|
||||
|
||||
public void Catch (object reject)
|
||||
{
|
||||
if (reject != null) _rejectCallbacks.Add (reject);
|
||||
}
|
||||
|
||||
public bool IsCompleted => _completed;
|
||||
public bool IsCancelled => _cancelled;
|
||||
public bool IsError => _error != null;
|
||||
|
||||
public object Error => _error;
|
||||
|
||||
public void Cancel ()
|
||||
{
|
||||
_cts.Cancel ();
|
||||
_cancelled = true;
|
||||
}
|
||||
|
||||
public void ReportProgress (object progress)
|
||||
{
|
||||
foreach (var cb in _progressCallbacks)
|
||||
JsUtils.Call (cb, progress);
|
||||
}
|
||||
|
||||
public object Result => _result;
|
||||
}
|
||||
[ComVisible (true)]
|
||||
[ClassInterface (ClassInterfaceType.AutoDual)]
|
||||
public class _I_Thread: _I_IAsyncAction
|
||||
{
|
||||
private Thread _thread;
|
||||
private bool _completed;
|
||||
private bool _cancelled;
|
||||
private Exception _error;
|
||||
private List<object> _resolveCallbacks = new List<object> ();
|
||||
private List<object> _rejectCallbacks = new List<object> ();
|
||||
private List<object> _progressCallbacks = new List<object> ();
|
||||
private CancellationTokenSource _cts = new CancellationTokenSource ();
|
||||
|
||||
public _I_Thread (Action action)
|
||||
{
|
||||
_thread = new Thread (() => {
|
||||
try
|
||||
{
|
||||
if (_cts.Token.IsCancellationRequested)
|
||||
{
|
||||
_cancelled = true;
|
||||
return;
|
||||
}
|
||||
|
||||
action ();
|
||||
_completed = true;
|
||||
|
||||
foreach (var cb in _resolveCallbacks)
|
||||
JsUtils.Call (cb);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_error = ex;
|
||||
foreach (var cb in _rejectCallbacks)
|
||||
JsUtils.Call (cb, ex);
|
||||
}
|
||||
});
|
||||
_thread.IsBackground = true;
|
||||
_thread.Start ();
|
||||
}
|
||||
|
||||
public _I_IAsyncAction Then (object resolve, object reject = null, object progress = null)
|
||||
{
|
||||
if (resolve != null) _resolveCallbacks.Add (resolve);
|
||||
if (reject != null) _rejectCallbacks.Add (reject);
|
||||
if (progress != null) _progressCallbacks.Add (progress);
|
||||
return this;
|
||||
}
|
||||
|
||||
public void Done (object resolve, object reject = null)
|
||||
{
|
||||
if (resolve != null) _resolveCallbacks.Add (resolve);
|
||||
if (reject != null) _rejectCallbacks.Add (reject);
|
||||
}
|
||||
|
||||
public void Catch (object reject)
|
||||
{
|
||||
if (reject != null) _rejectCallbacks.Add (reject);
|
||||
}
|
||||
|
||||
public bool IsCompleted => _completed;
|
||||
public bool IsCancelled => _cancelled;
|
||||
public bool IsError => _error != null;
|
||||
public object Error => _error;
|
||||
|
||||
public void Cancel ()
|
||||
{
|
||||
_cts.Cancel ();
|
||||
_cancelled = true;
|
||||
}
|
||||
|
||||
public void ReportProgress (object progress)
|
||||
{
|
||||
foreach (var cb in _progressCallbacks)
|
||||
JsUtils.Call (cb, progress);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,321 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Text;
|
||||
using Newtonsoft.Json;
|
||||
|
||||
namespace DataUtils
|
||||
{
|
||||
[ComVisible (true)]
|
||||
[InterfaceType (ComInterfaceType.InterfaceIsDual)]
|
||||
public interface IHttpResponse: IDisposable
|
||||
{
|
||||
int Status { get; } // 兼容旧版,等同于 StatusCode
|
||||
int StatusCode { get; }
|
||||
string StatusText { get; } // 等同于 StatusDescription
|
||||
string StatusDescription { get; }
|
||||
string ResponseUrl { get; }
|
||||
Uri ResponseUri { get; }
|
||||
string ContentType { get; }
|
||||
long ContentLength { get; } // 注意:JS 中 Number 可表示 2^53 以内整数
|
||||
string CharacterSet { get; }
|
||||
string ContentEncoding { get; }
|
||||
DateTime LastModified { get; }
|
||||
string Method { get; } // 原始请求方法 (GET, POST...)
|
||||
Version ProtocolVersion { get; } // 如 1.1,JS 中可能转为字符串
|
||||
bool IsFromCache { get; }
|
||||
bool IsMutuallyAuthenticated { get; }
|
||||
string Text ();
|
||||
_I_Enumerable Bytes ();
|
||||
}
|
||||
[ComVisible (true)]
|
||||
[ClassInterface (ClassInterfaceType.AutoDual)]
|
||||
public class HttpResponse: IHttpResponse, IDisposable
|
||||
{
|
||||
private readonly byte [] _data;
|
||||
private readonly Dictionary<string, string> _headersDict;
|
||||
private bool _disposed = false;
|
||||
public int Status => StatusCode;
|
||||
public int StatusCode { get; private set; }
|
||||
public string StatusText => StatusDescription;
|
||||
public string StatusDescription { get; private set; }
|
||||
public string ResponseUrl => ResponseUri?.ToString ();
|
||||
public Uri ResponseUri { get; private set; }
|
||||
public string ContentType { get; private set; }
|
||||
public long ContentLength { get; private set; }
|
||||
public string CharacterSet { get; private set; }
|
||||
public string ContentEncoding { get; private set; }
|
||||
public DateTime LastModified { get; private set; }
|
||||
public string Method { get; private set; }
|
||||
public Version ProtocolVersion { get; private set; }
|
||||
public bool IsFromCache { get; private set; }
|
||||
public bool IsMutuallyAuthenticated { get; private set; }
|
||||
public HttpResponse (HttpWebResponse response)
|
||||
{
|
||||
if (response == null) throw new ArgumentNullException (nameof (response));
|
||||
using (var stream = response.GetResponseStream ())
|
||||
using (var ms = new MemoryStream ())
|
||||
{
|
||||
stream.CopyTo (ms);
|
||||
_data = ms.ToArray ();
|
||||
}
|
||||
StatusCode = (int)response.StatusCode;
|
||||
StatusDescription = response.StatusDescription;
|
||||
ResponseUri = response.ResponseUri;
|
||||
Method = response.Method;
|
||||
ProtocolVersion = new Version ((ushort)response.ProtocolVersion.Major, (ushort)response.ProtocolVersion.Minor, (ushort)response.ProtocolVersion.Build, (ushort)response.ProtocolVersion.Revision);
|
||||
IsFromCache = response.IsFromCache;
|
||||
IsMutuallyAuthenticated = response.IsMutuallyAuthenticated;
|
||||
ContentType = response.ContentType ?? "";
|
||||
ContentLength = response.ContentLength;
|
||||
CharacterSet = response.CharacterSet ?? "";
|
||||
ContentEncoding = response.ContentEncoding ?? "";
|
||||
LastModified = response.LastModified;
|
||||
_headersDict = new Dictionary<string, string> (StringComparer.OrdinalIgnoreCase);
|
||||
foreach (string key in response.Headers.AllKeys)
|
||||
{
|
||||
if (!string.IsNullOrEmpty (key))
|
||||
_headersDict [key] = response.Headers [key];
|
||||
}
|
||||
}
|
||||
public HttpResponse (int statusCode, string statusDescription, string responseUrl, byte [] data, Dictionary<string, string> headers)
|
||||
{
|
||||
StatusCode = statusCode;
|
||||
StatusDescription = statusDescription ?? "";
|
||||
ResponseUri = string.IsNullOrEmpty (responseUrl) ? null : new Uri (responseUrl);
|
||||
_data = data ?? new byte [0];
|
||||
_headersDict = headers ?? new Dictionary<string, string> ();
|
||||
ContentType = GetHeader ("Content-Type") ?? "";
|
||||
ContentLength = _data.Length;
|
||||
CharacterSet = "";
|
||||
ContentEncoding = "";
|
||||
LastModified = DateTime.MinValue;
|
||||
Method = "";
|
||||
ProtocolVersion = new Version (0, 0);
|
||||
IsFromCache = false;
|
||||
IsMutuallyAuthenticated = false;
|
||||
}
|
||||
public string GetHeader (string sName)
|
||||
{
|
||||
if (string.IsNullOrEmpty (sName)) return null;
|
||||
try
|
||||
{
|
||||
return _headersDict [sName];
|
||||
}
|
||||
catch { return null; }
|
||||
}
|
||||
public string GetHeadersToJson ()
|
||||
{
|
||||
return JsonConvert.SerializeObject (_headersDict);
|
||||
}
|
||||
public string Text ()
|
||||
{
|
||||
string charset = CharacterSet;
|
||||
Encoding enc = Encoding.UTF8;
|
||||
if (!string.IsNullOrEmpty (charset))
|
||||
{
|
||||
try { enc = Encoding.GetEncoding (charset); }
|
||||
catch { /* 保持 UTF-8 */ }
|
||||
}
|
||||
return enc.GetString (_data);
|
||||
}
|
||||
public _I_Enumerable Bytes ()
|
||||
{
|
||||
var list = new List<object> ();
|
||||
foreach (byte b in _data)
|
||||
list.Add (b);
|
||||
return new _I_List (list);
|
||||
}
|
||||
public void Dispose ()
|
||||
{
|
||||
Dispose (true);
|
||||
GC.SuppressFinalize (this);
|
||||
}
|
||||
protected virtual void Dispose (bool disposing)
|
||||
{
|
||||
if (!_disposed)
|
||||
{
|
||||
_disposed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
[ComVisible (true)]
|
||||
[ClassInterface (ClassInterfaceType.AutoDual)]
|
||||
public class HttpRequest: IDisposable
|
||||
{
|
||||
private string _method;
|
||||
private string _url;
|
||||
private Dictionary<string, string> _headers = new Dictionary<string, string> ();
|
||||
public int Timeout { get; set; } = 100000; // 毫秒,默认 100 秒
|
||||
public int ReadWriteTimeout { get; set; } = 300000; // 读写超时,默认 5 分钟
|
||||
public bool AllowAutoRedirect { get; set; } = true;
|
||||
public bool AllowWriteStreamBuffering { get; set; } = true;
|
||||
public bool KeepAlive { get; set; } = true;
|
||||
public int MaximumAutomaticRedirections { get; set; } = 50;
|
||||
public string UserAgent
|
||||
{
|
||||
get { return GetHeader ("User-Agent"); }
|
||||
set { SetHeader ("User-Agent", value); }
|
||||
}
|
||||
public string Referer
|
||||
{
|
||||
get { return GetHeader ("Referer"); }
|
||||
set { SetHeader ("Referer", value); }
|
||||
}
|
||||
public string ContentType
|
||||
{
|
||||
get { return GetHeader ("Content-Type"); }
|
||||
set { SetHeader ("Content-Type", value); }
|
||||
}
|
||||
public string Accept
|
||||
{
|
||||
get { return GetHeader ("Accept"); }
|
||||
set { SetHeader ("Accept", value); }
|
||||
}
|
||||
public IWebProxy Proxy { get; set; } = null;
|
||||
public CookieContainer CookieContainer { get; set; } = null;
|
||||
private string _httpver = "1.1";
|
||||
public string ProtocolVersion
|
||||
{
|
||||
get { return _httpver; }
|
||||
set { _httpver = value; }
|
||||
}
|
||||
public System.Version ProtVer
|
||||
{
|
||||
get
|
||||
{
|
||||
switch (_httpver)
|
||||
{
|
||||
case "1.0": return HttpVersion.Version10;
|
||||
default:
|
||||
case "1.1": return HttpVersion.Version11;
|
||||
}
|
||||
}
|
||||
}
|
||||
public bool PreAuthenticate { get; set; } = false;
|
||||
public ICredentials Credentials { get; set; } = null;
|
||||
public bool AutomaticDecompression { get; set; } = false;
|
||||
public Action<long, long> UploadProgressCallback { get; set; } = null;
|
||||
public void Open (string sMethod, string sUrl)
|
||||
{
|
||||
_method = sMethod;
|
||||
_url = sUrl;
|
||||
}
|
||||
public void SetHeader (string sName, string sValue) => _headers [sName] = sValue;
|
||||
public string GetHeader (string sName) => _headers [sName];
|
||||
public string GetHeadersToJson () => JsonConvert.SerializeObject (_headers);
|
||||
public void RemoveHeader (string sName) => _headers.Remove (sName);
|
||||
public void ClearHeader () => _headers.Clear ();
|
||||
public IHttpResponse Send (string sBody, string encoding)
|
||||
{
|
||||
var req = (HttpWebRequest)WebRequest.Create (_url);
|
||||
req.Method = _method;
|
||||
req.Timeout = Timeout;
|
||||
req.ReadWriteTimeout = ReadWriteTimeout;
|
||||
req.AllowAutoRedirect = AllowAutoRedirect;
|
||||
req.AllowWriteStreamBuffering = AllowWriteStreamBuffering;
|
||||
req.KeepAlive = KeepAlive;
|
||||
req.MaximumAutomaticRedirections = MaximumAutomaticRedirections;
|
||||
if (Proxy != null) req.Proxy = Proxy;
|
||||
if (CookieContainer != null) req.CookieContainer = CookieContainer;
|
||||
req.ProtocolVersion = ProtVer;
|
||||
req.PreAuthenticate = PreAuthenticate;
|
||||
if (Credentials != null) req.Credentials = Credentials;
|
||||
if (AutomaticDecompression)
|
||||
req.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
|
||||
if (_headers.ContainsKey ("User-Agent"))
|
||||
req.UserAgent = _headers ["User-Agent"];
|
||||
foreach (var h in _headers)
|
||||
{
|
||||
if (string.Equals (h.Key, "User-Agent", StringComparison.OrdinalIgnoreCase))
|
||||
continue;
|
||||
if (string.Equals (h.Key, "Content-Type", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
string ct = h.Value;
|
||||
if (!string.IsNullOrEmpty (sBody) && !ct.Contains ("charset"))
|
||||
{
|
||||
Encoding enc = Encoding.GetEncoding (encoding);
|
||||
ct = ct + "; charset=" + enc.WebName;
|
||||
}
|
||||
req.ContentType = ct;
|
||||
}
|
||||
else if (string.Equals (h.Key, "Accept", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
req.Accept = h.Value;
|
||||
}
|
||||
else if (string.Equals (h.Key, "Referer", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
req.Referer = h.Value;
|
||||
}
|
||||
else
|
||||
{
|
||||
req.Headers [h.Key] = h.Value;
|
||||
}
|
||||
}
|
||||
|
||||
// 如果没有显式设置 Content-Type 且是 POST/PUT 且有请求体,设置默认值
|
||||
bool hasContentType = _headers.Keys.Any (k => string.Equals (k, "Content-Type", StringComparison.OrdinalIgnoreCase));
|
||||
if (!hasContentType && (string.Equals (_method, "POST", StringComparison.OrdinalIgnoreCase) ||
|
||||
string.Equals (_method, "PUT", StringComparison.OrdinalIgnoreCase)) &&
|
||||
!string.IsNullOrEmpty (sBody))
|
||||
{
|
||||
Encoding enc = Encoding.GetEncoding (encoding);
|
||||
req.ContentType = "application/x-www-form-urlencoded; charset=" + enc.WebName;
|
||||
}
|
||||
|
||||
// 写入请求体
|
||||
if (!string.IsNullOrEmpty (sBody))
|
||||
{
|
||||
Encoding enc = Encoding.GetEncoding (encoding);
|
||||
byte [] bytes = enc.GetBytes (sBody);
|
||||
req.ContentLength = bytes.Length;
|
||||
using (var stream = req.GetRequestStream ())
|
||||
{
|
||||
if (UploadProgressCallback != null)
|
||||
{
|
||||
int totalWritten = 0;
|
||||
int bufferSize = 8192;
|
||||
for (int offset = 0; offset < bytes.Length; offset += bufferSize)
|
||||
{
|
||||
int chunkSize = Math.Min (bufferSize, bytes.Length - offset);
|
||||
stream.Write (bytes, offset, chunkSize);
|
||||
totalWritten += chunkSize;
|
||||
UploadProgressCallback (totalWritten, bytes.Length);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
stream.Write (bytes, 0, bytes.Length);
|
||||
}
|
||||
}
|
||||
}
|
||||
using (var res = (HttpWebResponse)req.GetResponse ())
|
||||
{
|
||||
return new HttpResponse (res);
|
||||
}
|
||||
}
|
||||
public void SendAsync (string sBody, string encoding, object pfResolve)
|
||||
{
|
||||
System.Threading.ThreadPool.QueueUserWorkItem (delegate
|
||||
{
|
||||
JsUtils.Call (pfResolve, Send (sBody, encoding));
|
||||
});
|
||||
}
|
||||
public void Dispose () { }
|
||||
}
|
||||
[ComVisible (true)]
|
||||
[ClassInterface (ClassInterfaceType.AutoDual)]
|
||||
public class _I_Http
|
||||
{
|
||||
public HttpRequest CreateHttpRequest () => new HttpRequest ();
|
||||
}
|
||||
[ComVisible (true)]
|
||||
[ClassInterface (ClassInterfaceType.AutoDual)]
|
||||
public class _I_Web
|
||||
{
|
||||
public _I_Http Http => new _I_Http ();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user