123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434 |
- using System;
- using System.Collections;
- using System.Collections.Generic;
- using System.IO;
- using System.Text;
- namespace BestHTTP
- {
- using BestHTTP.Authentication;
- using BestHTTP.Extensions;
- using BestHTTP.Forms;
- #if !BESTHTTP_DISABLE_COOKIES && (!UNITY_WEBGL || UNITY_EDITOR)
- using BestHTTP.Cookies;
- #endif
-
-
-
- public enum HTTPRequestStates
- {
-
-
-
- Initial,
-
-
-
- Queued,
-
-
-
- Processing,
-
-
-
- Finished,
-
-
-
- Error,
-
-
-
- Aborted,
-
-
-
- ConnectionTimedOut,
-
-
-
- TimedOut
- }
- public delegate void OnRequestFinishedDelegate(HTTPRequest originalRequest, HTTPResponse response);
- public delegate void OnDownloadProgressDelegate(HTTPRequest originalRequest, long downloaded, long downloadLength);
- public delegate void OnUploadProgressDelegate(HTTPRequest originalRequest, long uploaded, long uploadLength);
- public delegate bool OnBeforeRedirectionDelegate(HTTPRequest originalRequest, HTTPResponse response, Uri redirectUri);
- public delegate void OnHeaderEnumerationDelegate(string header, List<string> values);
- public delegate void OnBeforeHeaderSendDelegate(HTTPRequest req);
-
-
-
- public sealed class HTTPRequest : IEnumerator, IEnumerator<HTTPRequest>
- {
- #region Statics
- public static readonly byte[] EOL = { HTTPResponse.CR, HTTPResponse.LF };
-
-
-
- public static readonly string[] MethodNames = {
- HTTPMethods.Get.ToString().ToUpper(),
- HTTPMethods.Head.ToString().ToUpper(),
- HTTPMethods.Post.ToString().ToUpper(),
- HTTPMethods.Put.ToString().ToUpper(),
- HTTPMethods.Delete.ToString().ToUpper(),
- HTTPMethods.Patch.ToString().ToUpper(),
- HTTPMethods.Merge.ToString().ToUpper(),
- HTTPMethods.Options.ToString().ToUpper()
- };
-
-
-
- public static int UploadChunkSize = 2 * 1024;
- #endregion
- #region Properties
-
-
-
- public Uri Uri { get; private set; }
-
-
-
- public HTTPMethods MethodType { get; set; }
-
-
-
- public byte[] RawData { get; set; }
-
-
-
- public Stream UploadStream { get; set; }
-
-
-
- public bool DisposeUploadStream { get; set; }
-
-
-
- public bool UseUploadStreamLength { get; set; }
-
-
-
- public OnUploadProgressDelegate OnUploadProgress;
-
-
-
-
- public bool IsKeepAlive
- {
- get { return isKeepAlive; }
- set
- {
- if (State == HTTPRequestStates.Processing)
- throw new NotSupportedException("Changing the IsKeepAlive property while processing the request is not supported.");
- isKeepAlive = value;
- }
- }
- #if !BESTHTTP_DISABLE_CACHING && (!UNITY_WEBGL || UNITY_EDITOR)
-
-
-
- public bool DisableCache
- {
- get { return disableCache; }
- set
- {
- if (State == HTTPRequestStates.Processing)
- throw new NotSupportedException("Changing the DisableCache property while processing the request is not supported.");
- disableCache = value;
- }
- }
- public bool CacheOnly
- {
- get { return cacheOnly; }
- set
- {
- if (State == HTTPRequestStates.Processing)
- throw new NotSupportedException("Changing the CacheOnly property while processing the request is not supported.");
- cacheOnly = value;
- }
- }
- #endif
-
-
-
- public bool UseStreaming
- {
- get { return useStreaming; }
- set
- {
- if (State == HTTPRequestStates.Processing)
- throw new NotSupportedException("Changing the UseStreaming property while processing the request is not supported.");
- useStreaming = value;
- }
- }
-
-
-
- public int StreamFragmentSize
- {
- get{ return streamFragmentSize; }
- set
- {
- if (State == HTTPRequestStates.Processing)
- throw new NotSupportedException("Changing the StreamFragmentSize property while processing the request is not supported.");
- if (value < 1)
- throw new System.ArgumentException("StreamFragmentSize must be at least 1.");
- streamFragmentSize = value;
- }
- }
- public int MaxFragmentQueueLength { get; set; }
-
-
-
- public OnRequestFinishedDelegate Callback { get; set; }
-
-
-
-
-
- public OnDownloadProgressDelegate OnProgress;
-
-
-
- public OnRequestFinishedDelegate OnUpgraded;
-
-
-
- public bool DisableRetry { get; set; }
-
-
-
- public bool IsRedirected { get; internal set; }
-
-
-
- public Uri RedirectUri { get; internal set; }
-
-
-
- public Uri CurrentUri { get { return IsRedirected ? RedirectUri : Uri; } }
-
-
-
-
- public HTTPResponse Response { get; internal set; }
- #if !BESTHTTP_DISABLE_PROXY
-
-
-
- public HTTPResponse ProxyResponse { get; internal set; }
- #endif
-
-
-
- public Exception Exception { get; internal set; }
-
-
-
- public object Tag { get; set; }
-
-
-
- public Credentials Credentials { get; set; }
- #if !BESTHTTP_DISABLE_PROXY
-
-
-
- public bool HasProxy { get { return Proxy != null; } }
-
-
-
- public HTTPProxy Proxy { get; set; }
- #endif
-
-
-
- public int MaxRedirects { get; set; }
- #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
-
-
-
- public bool UseAlternateSSL { get; set; }
- #endif
- #if !BESTHTTP_DISABLE_COOKIES && (!UNITY_WEBGL || UNITY_EDITOR)
-
-
-
- public bool IsCookiesEnabled { get; set; }
-
-
-
- public List<Cookie> Cookies
- {
- get
- {
- if (customCookies == null)
- customCookies = new List<Cookie>();
- return customCookies;
- }
- set { customCookies = value; }
- }
- private List<Cookie> customCookies;
- #endif
-
-
-
- public HTTPFormUsage FormUsage { get; set; }
-
-
-
- public HTTPRequestStates State { get; internal set; }
-
-
-
- public int RedirectCount { get; internal set; }
- #if !NETFX_CORE && !UNITY_WP8
-
-
-
-
- public event System.Func<HTTPRequest, System.Security.Cryptography.X509Certificates.X509Certificate, System.Security.Cryptography.X509Certificates.X509Chain, bool> CustomCertificationValidator;
- #endif
-
-
-
- public TimeSpan ConnectTimeout { get; set; }
-
-
-
-
- public TimeSpan Timeout { get; set; }
-
-
-
- public bool EnableTimoutForStreaming { get; set; }
-
-
-
- public bool EnableSafeReadOnUnknownContentLength { get; set; }
-
-
-
- public int Priority { get; set; }
- #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
-
-
-
- public Org.BouncyCastle.Crypto.Tls.ICertificateVerifyer CustomCertificateVerifyer { get; set; }
-
-
-
- public Org.BouncyCastle.Crypto.Tls.IClientCredentialsProvider CustomClientCredentialsProvider { get; set; }
-
-
-
-
-
-
- public List<string> CustomTLSServerNameList { get; set; }
- #endif
-
-
-
- public SupportedProtocols ProtocolHandler { get; set; }
-
-
-
-
- public event OnBeforeRedirectionDelegate OnBeforeRedirection
- {
- add { onBeforeRedirection += value; }
- remove { onBeforeRedirection -= value; }
- }
- private OnBeforeRedirectionDelegate onBeforeRedirection;
-
-
-
- public event OnBeforeHeaderSendDelegate OnBeforeHeaderSend
- {
- add { _onBeforeHeaderSend += value; }
- remove { _onBeforeHeaderSend -= value; }
- }
- private OnBeforeHeaderSendDelegate _onBeforeHeaderSend;
-
-
-
- public bool TryToMinimizeTCPLatency { get; set; }
- #region Internal Properties For Progress Report Support
-
-
-
- internal long Downloaded { get; set; }
-
-
-
-
-
- internal long DownloadLength { get; set; }
-
-
-
- internal bool DownloadProgressChanged { get; set; }
-
-
-
- internal long UploadStreamLength
- {
- get
- {
- if (UploadStream == null || !UseUploadStreamLength)
- return -1;
- try
- {
-
- return UploadStream.Length;
- }
- catch
- {
-
- return -1;
- }
- }
- }
-
-
-
- internal long Uploaded { get; set; }
-
-
-
- internal long UploadLength { get; set; }
-
-
-
- internal bool UploadProgressChanged { get; set; }
- #endregion
- #endregion
- #region Privates
- private bool isKeepAlive;
- #if !BESTHTTP_DISABLE_CACHING && (!UNITY_WEBGL || UNITY_EDITOR)
- private bool disableCache;
- private bool cacheOnly;
- #endif
- private int streamFragmentSize;
- private bool useStreaming;
- private Dictionary<string, List<string>> Headers { get; set; }
-
-
-
- private HTTPFormBase FieldCollector;
-
-
-
-
- private HTTPFormBase FormImpl;
- #endregion
- #region Constructors
- #region Default Get Constructors
- public HTTPRequest(Uri uri)
- : this(uri, HTTPMethods.Get, HTTPManager.KeepAliveDefaultValue,
- #if !BESTHTTP_DISABLE_CACHING && (!UNITY_WEBGL || UNITY_EDITOR)
- HTTPManager.IsCachingDisabled
- #else
- true
- #endif
- , null)
- {
- }
- public HTTPRequest(Uri uri, OnRequestFinishedDelegate callback)
- : this(uri, HTTPMethods.Get, HTTPManager.KeepAliveDefaultValue,
- #if !BESTHTTP_DISABLE_CACHING && (!UNITY_WEBGL || UNITY_EDITOR)
- HTTPManager.IsCachingDisabled
- #else
- true
- #endif
- , callback)
- {
- }
- public HTTPRequest(Uri uri, bool isKeepAlive, OnRequestFinishedDelegate callback)
- : this(uri, HTTPMethods.Get, isKeepAlive,
- #if !BESTHTTP_DISABLE_CACHING && (!UNITY_WEBGL || UNITY_EDITOR)
- HTTPManager.IsCachingDisabled
- #else
- true
- #endif
- , callback)
- {
- }
- public HTTPRequest(Uri uri, bool isKeepAlive, bool disableCache, OnRequestFinishedDelegate callback)
- : this(uri, HTTPMethods.Get, isKeepAlive, disableCache, callback)
- {
- }
- #endregion
- public HTTPRequest(Uri uri, HTTPMethods methodType)
- : this(uri, methodType, HTTPManager.KeepAliveDefaultValue,
- #if !BESTHTTP_DISABLE_CACHING && (!UNITY_WEBGL || UNITY_EDITOR)
- HTTPManager.IsCachingDisabled || methodType != HTTPMethods.Get
- #else
- true
- #endif
- , null)
- {
- }
- public HTTPRequest(Uri uri, HTTPMethods methodType, OnRequestFinishedDelegate callback)
- : this(uri, methodType, HTTPManager.KeepAliveDefaultValue,
- #if !BESTHTTP_DISABLE_CACHING && (!UNITY_WEBGL || UNITY_EDITOR)
- HTTPManager.IsCachingDisabled || methodType != HTTPMethods.Get
- #else
- true
- #endif
- , callback)
- {
- }
- public HTTPRequest(Uri uri, HTTPMethods methodType, bool isKeepAlive, OnRequestFinishedDelegate callback)
- : this(uri, methodType, isKeepAlive,
- #if !BESTHTTP_DISABLE_CACHING && (!UNITY_WEBGL || UNITY_EDITOR)
- HTTPManager.IsCachingDisabled || methodType != HTTPMethods.Get
- #else
- true
- #endif
- , callback)
- {
- }
- public HTTPRequest(Uri uri, HTTPMethods methodType, bool isKeepAlive, bool disableCache, OnRequestFinishedDelegate callback)
- {
- this.Uri = uri;
- this.MethodType = methodType;
- this.IsKeepAlive = isKeepAlive;
- #if !BESTHTTP_DISABLE_CACHING && (!UNITY_WEBGL || UNITY_EDITOR)
- this.DisableCache = disableCache;
- #endif
- this.Callback = callback;
- this.StreamFragmentSize = 4 * 1024;
- this.MaxFragmentQueueLength = 10;
- this.DisableRetry = !(methodType == HTTPMethods.Get);
- this.MaxRedirects = int.MaxValue;
- this.RedirectCount = 0;
- #if !BESTHTTP_DISABLE_COOKIES && (!UNITY_WEBGL || UNITY_EDITOR)
- this.IsCookiesEnabled = HTTPManager.IsCookiesEnabled;
- #endif
- this.Downloaded = DownloadLength = 0;
- this.DownloadProgressChanged = false;
- this.State = HTTPRequestStates.Initial;
- this.ConnectTimeout = HTTPManager.ConnectTimeout;
- this.Timeout = HTTPManager.RequestTimeout;
- this.EnableTimoutForStreaming = false;
- this.EnableSafeReadOnUnknownContentLength = true;
- #if !BESTHTTP_DISABLE_PROXY
- this.Proxy = HTTPManager.Proxy;
- #endif
- this.UseUploadStreamLength = true;
- this.DisposeUploadStream = true;
- #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
- this.CustomCertificateVerifyer = HTTPManager.DefaultCertificateVerifyer;
- this.CustomClientCredentialsProvider = HTTPManager.DefaultClientCredentialsProvider;
- this.UseAlternateSSL = HTTPManager.UseAlternateSSLDefaultValue;
- #endif
- #if !NETFX_CORE && !UNITY_WP8
- this.CustomCertificationValidator += HTTPManager.DefaultCertificationValidator;
- #endif
- this.TryToMinimizeTCPLatency = HTTPManager.TryToMinimizeTCPLatency;
- }
- #endregion
- #region Public Field Functions
-
-
-
- public void AddField(string fieldName, string value)
- {
- AddField(fieldName, value, System.Text.Encoding.UTF8);
- }
-
-
-
- public void AddField(string fieldName, string value, System.Text.Encoding e)
- {
- if (FieldCollector == null)
- FieldCollector = new HTTPFormBase();
- FieldCollector.AddField(fieldName, value, e);
- }
-
-
-
- public void AddBinaryData(string fieldName, byte[] content)
- {
- AddBinaryData(fieldName, content, null, null);
- }
-
-
-
- public void AddBinaryData(string fieldName, byte[] content, string fileName)
- {
- AddBinaryData(fieldName, content, fileName, null);
- }
-
-
-
- public void AddBinaryData(string fieldName, byte[] content, string fileName, string mimeType)
- {
- if (FieldCollector == null)
- FieldCollector = new HTTPFormBase();
- FieldCollector.AddBinaryData(fieldName, content, fileName, mimeType);
- }
- #if !BESTHTTP_DISABLE_UNITY_FORM
-
-
-
- public void SetFields(UnityEngine.WWWForm wwwForm)
- {
- FormUsage = HTTPFormUsage.Unity;
- FormImpl = new UnityForm(wwwForm);
- }
- #endif
-
-
-
- public void SetForm(HTTPFormBase form)
- {
- FormImpl = form;
- }
-
-
-
- public List<HTTPFieldData> GetFormFields()
- {
- if (this.FieldCollector == null || this.FieldCollector.IsEmpty)
- return null;
- return new List<HTTPFieldData>(this.FieldCollector.Fields);
- }
-
-
-
- public void ClearForm()
- {
- FormImpl = null;
- FieldCollector = null;
- }
-
-
-
- private HTTPFormBase SelectFormImplementation()
- {
-
- if (FormImpl != null)
- return FormImpl;
-
- if (FieldCollector == null)
- return null;
- switch (FormUsage)
- {
- case HTTPFormUsage.Automatic:
-
-
- if (FieldCollector.HasBinary || FieldCollector.HasLongValue)
- goto case HTTPFormUsage.Multipart;
- else
- goto case HTTPFormUsage.UrlEncoded;
- case HTTPFormUsage.UrlEncoded: FormImpl = new HTTPUrlEncodedForm(); break;
- case HTTPFormUsage.Multipart: FormImpl = new HTTPMultiPartForm(); break;
- case HTTPFormUsage.RawJSon: FormImpl = new RawJsonForm(); break;
- #if !BESTHTTP_DISABLE_UNITY_FORM
- case HTTPFormUsage.Unity: FormImpl = new UnityForm(); break;
- #endif
- }
-
- FormImpl.CopyFrom(FieldCollector);
- return FormImpl;
- }
- #endregion
- #region Header Management
- #region General Management
-
-
-
-
- public void AddHeader(string name, string value)
- {
- if (Headers == null)
- Headers = new Dictionary<string, List<string>>();
- List<string> values;
- if (!Headers.TryGetValue(name, out values))
- Headers.Add(name, values = new List<string>(1));
- values.Add(value);
- }
-
-
-
- public void SetHeader(string name, string value)
- {
- if (Headers == null)
- Headers = new Dictionary<string, List<string>>();
- List<string> values;
- if (!Headers.TryGetValue(name, out values))
- Headers.Add(name, values = new List<string>(1));
- values.Clear();
- values.Add(value);
- }
-
-
-
-
-
- public bool RemoveHeader(string name)
- {
- if (Headers == null)
- return false;
- return Headers.Remove(name);
- }
-
-
-
- public bool HasHeader(string name)
- {
- return Headers != null && Headers.ContainsKey(name);
- }
-
-
-
- public string GetFirstHeaderValue(string name)
- {
- if (Headers == null)
- return null;
- List<string> headers = null;
- if (Headers.TryGetValue(name, out headers) && headers.Count > 0)
- return headers[0];
- return null;
- }
-
-
-
- public List<string> GetHeaderValues(string name)
- {
- if (Headers == null)
- return null;
- List<string> headers = null;
- if (Headers.TryGetValue(name, out headers) && headers.Count > 0)
- return headers;
- return null;
- }
- public void RemoveHeaders()
- {
- if (Headers == null)
- return;
- Headers.Clear();
- }
- #endregion
- #region Range Headers
-
-
-
-
- public void SetRangeHeader(int firstBytePos)
- {
- SetHeader("Range", string.Format("bytes={0}-", firstBytePos));
- }
-
-
-
-
-
- public void SetRangeHeader(int firstBytePos, int lastBytePos)
- {
- SetHeader("Range", string.Format("bytes={0}-{1}", firstBytePos, lastBytePos));
- }
- #endregion
- public void EnumerateHeaders(OnHeaderEnumerationDelegate callback)
- {
- EnumerateHeaders(callback, false);
- }
- public void EnumerateHeaders(OnHeaderEnumerationDelegate callback, bool callBeforeSendCallback)
- {
- #if !UNITY_WEBGL || UNITY_EDITOR
- if (!HasHeader("Host"))
- SetHeader("Host", CurrentUri.Authority);
- if (IsRedirected && !HasHeader("Referer"))
- AddHeader("Referer", Uri.ToString());
- if (!HasHeader("Accept-Encoding"))
- #if BESTHTTP_DISABLE_GZIP
- AddHeader("Accept-Encoding", "identity");
- #else
- AddHeader("Accept-Encoding", "gzip, identity");
- #endif
- #if !BESTHTTP_DISABLE_PROXY
- if (HasProxy && !HasHeader("Proxy-Connection"))
- AddHeader("Proxy-Connection", IsKeepAlive ? "Keep-Alive" : "Close");
- #endif
- if (!HasHeader("Connection"))
- AddHeader("Connection", IsKeepAlive ? "Keep-Alive, TE" : "Close, TE");
- if (!HasHeader("TE"))
- AddHeader("TE", "identity");
- if (!HasHeader("User-Agent"))
- AddHeader("User-Agent", "BestHTTP");
- #endif
- long contentLength = -1;
- if (UploadStream == null)
- {
- byte[] entityBody = GetEntityBody();
- contentLength = entityBody != null ? entityBody.Length : 0;
- if (RawData == null && (FormImpl != null || (FieldCollector != null && !FieldCollector.IsEmpty)))
- {
- SelectFormImplementation();
- if (FormImpl != null)
- FormImpl.PrepareRequest(this);
- }
- }
- else
- {
- contentLength = UploadStreamLength;
- if (contentLength == -1)
- SetHeader("Transfer-Encoding", "Chunked");
- if (!HasHeader("Content-Type"))
- SetHeader("Content-Type", "application/octet-stream");
- }
-
-
-
- if (
- #if !UNITY_WEBGL || UNITY_EDITOR
- contentLength >= 0
- #else
- contentLength != -1
- #endif
- && !HasHeader("Content-Length"))
- SetHeader("Content-Length", contentLength.ToString());
- #if !UNITY_WEBGL || UNITY_EDITOR
- #if !BESTHTTP_DISABLE_PROXY
-
- if (HasProxy && Proxy.Credentials != null)
- {
- switch (Proxy.Credentials.Type)
- {
- case AuthenticationTypes.Basic:
-
- SetHeader("Proxy-Authorization", string.Concat("Basic ", Convert.ToBase64String(Encoding.UTF8.GetBytes(Proxy.Credentials.UserName + ":" + Proxy.Credentials.Password))));
- break;
- case AuthenticationTypes.Unknown:
- case AuthenticationTypes.Digest:
- var digest = DigestStore.Get(Proxy.Address);
- if (digest != null)
- {
- string authentication = digest.GenerateResponseHeader(this, Proxy.Credentials);
- if (!string.IsNullOrEmpty(authentication))
- SetHeader("Proxy-Authorization", authentication);
- }
- break;
- }
- }
- #endif
- #endif
-
- if (Credentials != null)
- {
- switch (Credentials.Type)
- {
- case AuthenticationTypes.Basic:
-
- SetHeader("Authorization", string.Concat("Basic ", Convert.ToBase64String(Encoding.UTF8.GetBytes(Credentials.UserName + ":" + Credentials.Password))));
- break;
- case AuthenticationTypes.Unknown:
- case AuthenticationTypes.Digest:
- var digest = DigestStore.Get(this.CurrentUri);
- if (digest != null)
- {
- string authentication = digest.GenerateResponseHeader(this, Credentials);
- if (!string.IsNullOrEmpty(authentication))
- SetHeader("Authorization", authentication);
- }
- break;
- }
- }
-
- #if !BESTHTTP_DISABLE_COOKIES && (!UNITY_WEBGL || UNITY_EDITOR)
-
- List<Cookie> cookies = IsCookiesEnabled ? CookieJar.Get(CurrentUri) : null;
-
- if (cookies == null || cookies.Count == 0)
- cookies = this.customCookies;
- else if (this.customCookies != null)
- {
-
- int idx = 0;
- while (idx < this.customCookies.Count)
- {
- Cookie customCookie = customCookies[idx];
- int foundIdx = cookies.FindIndex(c => c.Name.Equals(customCookie.Name));
- if (foundIdx >= 0)
- cookies[foundIdx] = customCookie;
- else
- cookies.Add(customCookie);
- idx++;
- }
- }
-
-
- if (cookies != null && cookies.Count > 0)
- {
-
-
-
-
- bool first = true;
- string cookieStr = string.Empty;
- bool isSecureProtocolInUse = HTTPProtocolFactory.IsSecureProtocol(CurrentUri);
- foreach (var cookie in cookies)
- if (!cookie.IsSecure || (cookie.IsSecure && isSecureProtocolInUse))
- {
- if (!first)
- cookieStr += "; ";
- else
- first = false;
- cookieStr += cookie.ToString();
-
- cookie.LastAccess = DateTime.UtcNow;
- }
- if (!string.IsNullOrEmpty(cookieStr))
- SetHeader("Cookie", cookieStr);
- }
- #endif
- if (callBeforeSendCallback && _onBeforeHeaderSend != null)
- {
- try
- {
- _onBeforeHeaderSend(this);
- }
- catch(Exception ex)
- {
- HTTPManager.Logger.Exception("HTTPRequest", "OnBeforeHeaderSend", ex);
- }
- }
-
- if (callback != null && Headers != null)
- foreach (var kvp in Headers)
- callback(kvp.Key, kvp.Value);
- }
-
-
-
- private void SendHeaders(Stream stream)
- {
- EnumerateHeaders((header, values) =>
- {
- if (string.IsNullOrEmpty(header) || values == null)
- return;
- byte[] headerName = string.Concat(header, ": ").GetASCIIBytes();
- for (int i = 0; i < values.Count; ++i)
- {
- if (string.IsNullOrEmpty(values[i]))
- {
- HTTPManager.Logger.Warning("HTTPRequest", string.Format("Null/empty value for header: {0}", header));
- continue;
- }
- if (HTTPManager.Logger.Level <= Logger.Loglevels.Information)
- VerboseLogging("Header - '" + header + "': '" + values[i] + "'");
- stream.WriteArray(headerName);
- stream.WriteArray(values[i].GetASCIIBytes());
- stream.WriteArray(EOL);
- }
- }, true);
- }
-
-
-
- public string DumpHeaders()
- {
- using (var ms = new MemoryStream())
- {
- SendHeaders(ms);
- return ms.ToArray().AsciiToString();
- }
- }
-
-
-
-
- public byte[] GetEntityBody()
- {
- if (RawData != null)
- return RawData;
- if (FormImpl != null || (FieldCollector != null && !FieldCollector.IsEmpty))
- {
- SelectFormImplementation();
- if (FormImpl != null)
- return FormImpl.GetData();
- }
- return null;
- }
- #endregion
- #region Internal Helper Functions
- internal void SendOutTo(Stream stream)
- {
-
- #if !UNITY_WEBGL || UNITY_EDITOR
- try
- {
- string requestPathAndQuery =
- #if !BESTHTTP_DISABLE_PROXY
- HasProxy && Proxy.SendWholeUri ? CurrentUri.OriginalString :
- #endif
- CurrentUri.GetRequestPathAndQueryURL();
- string requestLine = string.Format("{0} {1} HTTP/1.1", MethodNames[(byte)MethodType], requestPathAndQuery);
- if (HTTPManager.Logger.Level <= Logger.Loglevels.Information)
- HTTPManager.Logger.Information("HTTPRequest", string.Format("Sending request: '{0}'", requestLine));
-
-
-
- WriteOnlyBufferedStream bufferStream = new WriteOnlyBufferedStream(stream, (int)(UploadChunkSize * 1.5f));
- bufferStream.WriteArray(requestLine.GetASCIIBytes());
- bufferStream.WriteArray(EOL);
-
- SendHeaders(bufferStream);
- bufferStream.WriteArray(EOL);
-
- bufferStream.Flush();
- byte[] data = RawData;
-
- if (data == null && FormImpl != null)
- data = FormImpl.GetData();
- if (data != null || UploadStream != null)
- {
-
- Stream uploadStream = UploadStream;
- if (uploadStream == null)
- {
-
- uploadStream = new MemoryStream(data, 0, data.Length);
-
- UploadLength = data.Length;
- }
- else
- UploadLength = UseUploadStreamLength ? UploadStreamLength : -1;
-
- Uploaded = 0;
-
- byte[] buffer = new byte[UploadChunkSize];
-
- int count = 0;
- while ((count = uploadStream.Read(buffer, 0, buffer.Length)) > 0)
- {
-
- if (!UseUploadStreamLength)
- {
- bufferStream.WriteArray(count.ToString("X").GetASCIIBytes());
- bufferStream.WriteArray(EOL);
- }
-
- bufferStream.Write(buffer, 0, count);
-
- if (!UseUploadStreamLength)
- bufferStream.WriteArray(EOL);
-
- Uploaded += count;
-
- bufferStream.Flush();
-
- UploadProgressChanged = true;
- }
-
- if (!UseUploadStreamLength)
- {
- bufferStream.WriteArray("0".GetASCIIBytes());
- bufferStream.WriteArray(EOL);
- bufferStream.WriteArray(EOL);
- }
-
- bufferStream.Flush();
-
- if (UploadStream == null && uploadStream != null)
- uploadStream.Dispose();
- }
- else
- bufferStream.Flush();
- HTTPManager.Logger.Information("HTTPRequest", "'" + requestLine + "' sent out");
- }
- finally
- {
- if (UploadStream != null && DisposeUploadStream)
- UploadStream.Dispose();
- }
- #endif
- }
- internal void UpgradeCallback()
- {
- if (Response == null || !Response.IsUpgraded)
- return;
- try
- {
- if (OnUpgraded != null)
- OnUpgraded(this, Response);
- }
- catch (Exception ex)
- {
- HTTPManager.Logger.Exception("HTTPRequest", "UpgradeCallback", ex);
- }
- }
- internal void CallCallback()
- {
- try
- {
- if (this.Callback != null)
- this.Callback(this, Response);
- }
- catch (Exception ex)
- {
- HTTPManager.Logger.Exception("HTTPRequest", "CallCallback", ex);
- }
- }
- internal bool CallOnBeforeRedirection(Uri redirectUri)
- {
- if (onBeforeRedirection != null)
- return onBeforeRedirection(this, this.Response, redirectUri);
- return true;
- }
- internal void FinishStreaming()
- {
- if (Response != null && UseStreaming)
- Response.FinishStreaming();
- }
-
-
-
- internal void Prepare()
- {
- #if !BESTHTTP_DISABLE_UNITY_FORM
- if (FormUsage == HTTPFormUsage.Unity)
- SelectFormImplementation();
- #endif
- }
- #if !NETFX_CORE && !UNITY_WP8
- internal bool CallCustomCertificationValidator(System.Security.Cryptography.X509Certificates.X509Certificate cert, System.Security.Cryptography.X509Certificates.X509Chain chain)
- {
- if (CustomCertificationValidator != null)
- return CustomCertificationValidator(this, cert, chain);
- return true;
- }
- #endif
- #endregion
-
-
-
- public HTTPRequest Send()
- {
- return HTTPManager.SendRequest(this);
- }
-
-
-
- public void Abort()
- {
- if (System.Threading.Monitor.TryEnter(HTTPManager.Locker, TimeSpan.FromMilliseconds(100)))
- {
- try
- {
- if (this.State >= HTTPRequestStates.Finished)
- {
- HTTPManager.Logger.Warning("HTTPRequest", string.Format("Abort - Already in a state({0}) where no Abort required!", this.State.ToString()));
- return;
- }
-
- var connection = HTTPManager.GetConnectionWith(this);
-
- if (connection == null)
- {
-
- if (!HTTPManager.RemoveFromQueue(this))
- HTTPManager.Logger.Warning("HTTPRequest", "Abort - No active connection found with this request! (The request may already finished?)");
- this.State = HTTPRequestStates.Aborted;
- this.CallCallback();
- }
- else
- {
-
- if (Response != null && Response.IsStreamed)
- Response.Dispose();
-
- connection.Abort(HTTPConnectionStates.AbortRequested);
- }
- }
- finally
- {
- System.Threading.Monitor.Exit(HTTPManager.Locker);
- }
- }
- else
- throw new Exception("Wasn't able to acquire a thread lock. Abort failed!");
- }
-
-
-
- public void Clear()
- {
- ClearForm();
- RemoveHeaders();
- this.IsRedirected = false;
- this.RedirectCount = 0;
- this.Downloaded = this.DownloadLength = 0;
- }
- private void VerboseLogging(string str)
- {
- HTTPManager.Logger.Verbose("HTTPRequest", "'" + this.CurrentUri.ToString() + "' - " + str);
- }
- #region System.Collections.IEnumerator implementation
- public object Current { get { return null; } }
- public bool MoveNext()
- {
- return this.State < HTTPRequestStates.Finished;
- }
- public void Reset()
- {
- throw new NotImplementedException();
- }
- #endregion
- HTTPRequest IEnumerator<HTTPRequest>.Current
- {
- get { return this; }
- }
- public void Dispose()
- {
- }
- }
- }
|