Exemple #1
0
        public HTTPRequest Request(HTTPMethods method, string path, OnAppRespondedDelegate callback, OnAppRespondedDelegate err)
        {
            return(new HTTPRequest(
                       new System.Uri(URI, path),
                       method,
                       (HTTPRequest request_, HTTPResponse response_) =>
            {
                if (request_.State != HTTPRequestStates.Finished)
                {
                    request_ = null;
                    Debug.Log("Request " + path + " returned null");
                    return;
                }

                var json = JSON.Parse(request_.Response.DataAsText);
                if (json != null && json["error"] == json["null"])
                {
                    try
                    {
                        callback(json);
                    }
                    catch
                    {
                        Debug.Log("Network request callback threw: " + method.ToString() + ":" + path);
                    }
                }
                else
                {
                    err(json);
                }
            }));
        }
Exemple #2
0
 private static void SendOfflineRequest(string endpoint, HTTPMethods method, ApiContainer responseContainer = null, Dictionary <string, object> requestParams = null)
 {
     foreach (object offlineQuery in offlineQueries)
     {
         Dictionary <string, object> dictionary = offlineQuery as Dictionary <string, object>;
         if (dictionary["url"].ToString() == endpoint)
         {
             object result = dictionary["result"];
             string s      = Json.Encode(result);
             byte[] data   = Encoding.UTF8.GetBytes(s);
             responseContainer.OnComplete(success: true, endpoint, 200, string.Empty, () => data, () => Json.Encode(result));
             if (!responseContainer.IsValid)
             {
                 if (responseContainer.OnError != null)
                 {
                     responseContainer.OnError(responseContainer);
                 }
             }
             else if (responseContainer.OnSuccess != null)
             {
                 responseContainer.OnSuccess(responseContainer);
             }
         }
     }
     Logger.LogErrorFormat(DebugLevel.API, "Query used by application in offline mode not found - {0}", endpoint);
     responseContainer.Error = "query not found in offline results - " + endpoint;
     if (responseContainer.OnError != null)
     {
         responseContainer.OnError(responseContainer);
     }
 }
Exemple #3
0
        public HTTPRequest(Uri uri, HTTPMethods methodType, bool isKeepAlive, bool disableCache, OnRequestFinishedDelegate callback)
        {
            this.Uri                = uri;
            this.MethodType         = methodType;
            this.IsKeepAlive        = isKeepAlive;
            this.DisableCache       = disableCache;
            this.Callback           = callback;
            this.StreamFragmentSize = 4096;
            this.DisableRetry       = (methodType == HTTPMethods.Post);
            this.MaxRedirects       = 2147483647;
            this.RedirectCount      = 0;
            this.IsCookiesEnabled   = HTTPManager.IsCookiesEnabled;
            int num = 0;

            this.DownloadLength          = num;
            this.Downloaded              = num;
            this.DownloadProgressChanged = false;
            this.State                     = HTTPRequestStates.Initial;
            this.ConnectTimeout            = HTTPManager.ConnectTimeout;
            this.Timeout                   = HTTPManager.RequestTimeout;
            this.EnableTimoutForStreaming  = false;
            this.Proxy                     = HTTPManager.Proxy;
            this.UseUploadStreamLength     = true;
            this.DisposeUploadStream       = true;
            this.CustomCertificateVerifyer = HTTPManager.DefaultCertificateVerifyer;
        }
Exemple #4
0
        internal static HTTPCacheFileInfo Store(Uri uri, HTTPMethods method, HTTPResponse response)
        {
            if (response == null || response.Data == null || response.Data.Length == 0)
            {
                return(null);
            }
            HTTPCacheFileInfo hTTPCacheFileInfo     = null;
            Dictionary <Uri, HTTPCacheFileInfo> obj = HTTPCacheService.Library;

            lock (obj)
            {
                if (!HTTPCacheService.Library.TryGetValue(uri, out hTTPCacheFileInfo))
                {
                    HTTPCacheService.Library.Add(uri, hTTPCacheFileInfo = new HTTPCacheFileInfo(uri));
                }
                try
                {
                    hTTPCacheFileInfo.Store(response);
                }
                catch
                {
                    HTTPCacheService.DeleteEntity(uri, true);
                    throw;
                }
            }
            return(hTTPCacheFileInfo);
        }
Exemple #5
0
    private HTTPRequest NewRequest(string url, HTTPMethods method, HttpManager.Callback callback)
    {
        return(new HTTPRequest(new Uri(url), method, true, true, (_request, _response) =>
        {
            switch (_request.State)
            {
            case HTTPRequestStates.Finished:
                if (_response.IsSuccess)
                {
                    OnSuccess(_response, callback);
                }
                else
                {
                    OnResponseError(_request, _response, callback);
                }
                break;

            case HTTPRequestStates.Error:
                OnRequestError(_request, _response, callback);
                break;

            case HTTPRequestStates.Aborted:
                OnRequestError(_request, _response, callback);
                break;

            case HTTPRequestStates.ConnectionTimedOut:
                OnRequestError(_request, _response, callback);
                break;

            case HTTPRequestStates.TimedOut:
                OnRequestError(_request, _response, callback);
                break;
            }
        }));
    }
        internal static HTTPCacheFileInfo Store(Uri uri, HTTPMethods method, HTTPResponse response)
        {
            if (response == null || response.Data == null || response.Data.Length == 0)
            {
                return(null);
            }
            if (!IsSupported)
            {
                return(null);
            }
            HTTPCacheFileInfo value = null;

            lock (Library)
            {
                if (!Library.TryGetValue(uri, out value))
                {
                    Library.Add(uri, value = new HTTPCacheFileInfo(uri));
                    UsedIndexes.Add(value.MappedNameIDX, value);
                }
                try
                {
                    value.Store(response);
                    return(value);
                }
                catch
                {
                    DeleteEntity(uri);
                    throw;
IL_0087:
                    return(value);
                }
            }
        }
Exemple #7
0
        internal static HTTPCacheFileInfo Store(Uri uri, HTTPMethods method, HTTPResponse response)
        {
            if (response == null || response.Data == null || response.Data.Length == 0)
            {
                return(null);
            }

            HTTPCacheFileInfo info = null;

            lock (Library)
            {
                if (!Library.TryGetValue(uri, out info))
                {
                    Library.Add(uri, info = new HTTPCacheFileInfo(uri));
                }

                try
                {
                    info.Store(response);
                }
                catch
                {
                    // If something happens while we write out the response, than we will delete it becouse it might be in an invalid state.
                    DeleteEntity(uri);

                    throw;
                }
            }

            return(info);
        }
Exemple #8
0
        /// <summary>
        /// Checks if the given response can be cached. http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.4
        /// </summary>
        /// <returns>Returns true if cacheable, false otherwise.</returns>
        internal static bool IsCacheble(Uri uri, HTTPMethods method, HTTPResponse response)
        {
            if (method != HTTPMethods.Get)
            {
                return(false);
            }

            if (response == null)
            {
                return(false);
            }

            // Already cached
            if (response.StatusCode == 304)
            {
                return(false);
            }

            if (response.StatusCode < 200 || response.StatusCode >= 400)
            {
                return(false);
            }

            //http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9.2
            var cacheControls = response.GetHeaderValues("cache-control");

            if (cacheControls != null)
            {
                if (cacheControls.Exists(headerValue => {
                    string value = headerValue.ToLower();
                    return(value.Contains("no-store") || value.Contains("no-cache"));
                }))
                {
                    return(false);
                }
            }

            var pragmas = response.GetHeaderValues("pragma");

            if (pragmas != null)
            {
                if (pragmas.Exists(headerValue => {
                    string value = headerValue.ToLower();
                    return(value.Contains("no-store") || value.Contains("no-cache"));
                }))
                {
                    return(false);
                }
            }

            // Responses with byte ranges not supported yet.
            var byteRanges = response.GetHeaderValues("content-range");

            if (byteRanges != null)
            {
                return(false);
            }

            return(true);
        }
Exemple #9
0
        public async Task <IActionResult> AddOrderForm(CreateUpdateFactoryProgramRecordDto entity)
        {
            #region 字段合法性验证
            //所属车间 必填
            if (entity.SpinningMillId == Guid.Empty)
            {
                return(Fail("车间信息必传!"));
            }
            //所属车间 有效
            HttpResponseMessage SpinningMillResult = await HTTPMethods.Get(_httpApiUrlStrs.Value.BusinessApiUrl + AjaxUrls["GetSpinningMillData"].ToString() + entity.SpinningMillId);

            if (SpinningMillResult.StatusCode != System.Net.HttpStatusCode.OK)
            {
                return(Fail("车间信息不存在!"));
            }
            //订单号 必填
            if (!string.IsNullOrEmpty(entity.Code))
            {
                return(Fail("订单号必填!"));
            }
            #endregion
            HttpResponseMessage result = await HTTPMethods.Post(_httpApiUrlStrs.Value.BusinessApiUrl + AjaxUrls["AddOrderForm"].ToString(), entity.ToJson());

            if (result.StatusCode == System.Net.HttpStatusCode.OK)
            {
                return(SuccessInfo("新增成功!"));
            }
            else
            {
                return(Fail("未知错误!"));
            }
        }
Exemple #10
0
        /// <summary>
        /// Build a request for backend
        /// </summary>
        /// <param name="type">Type.</param>
        /// <param name="endpoint">Endpoint.</param>
        void RequestBuilder(HTTPMethods type, string endpoint)
        {
            HTTPRequest request = new HTTPRequest(new Uri(BASE_URI + endpoint), type,
                                                  OnRequestFinished);

            request.Send();
        }
    public void HttpRequestByMothdType(HTTPMethods methodType, string param, bool isKeepAlive, bool disableCache, Action <int, string, string> callBack)
    {
        string url = BaseUrl + SubPath + param;

        HTTPManager.SendRequest(url, methodType, isKeepAlive, disableCache, (HTTPRequest originalRequest, HTTPResponse response) =>
        {
            if (response == null)
            {
                callBack(-1, "", "");
                return;
            }
            string responseStr = "";
            int result         = 0;
            string msg         = "";
            if (response.IsSuccess)
            {
                responseStr = Encoding.UTF8.GetString(response.Data);
            }
            else
            {
                result = response.StatusCode;
                msg    = response.Message;
            }
            if (callBack != null)
            {
                callBack(result, msg, responseStr);
            }
        });
    }
        public IEnumerator RequestSync(string url,
                                       HTTPMethods methods = HTTPMethods.Get,
                                       Dictionary <string, string> headers = null,
                                       WWWForm param = null,
                                       Action <DownloadHandler> onSuccess = null,
                                       Action <float> onProgress          = null,
                                       Action <DownloadHandler> onError   = null)
        {
            HTTPRequest request = HTTPRequest.GenerateInstance();

            return(request.RequestSync(
                       url: url,
                       methods: methods,
                       headers: headers,
                       param: param,
                       onSuccess: (downloadHandler) =>
            {
                if (onSuccess != null)
                {
                    onSuccess(downloadHandler);
                }
                GameObject.Destroy(request.gameObject);
            },
                       onProgress: onProgress,
                       onError: (downloadHandler) =>
            {
                if (onError != null)
                {
                    onError(downloadHandler);
                }
                GameObject.Destroy(request.gameObject);
            }));
        }
Exemple #13
0
        public HTTPRequest(Uri uri, HTTPMethods methodType, bool isKeepAlive, bool disableCache, OnRequestFinishedDelegate callback)
        {
            Uri                = uri;
            MethodType         = methodType;
            IsKeepAlive        = isKeepAlive;
            DisableCache       = disableCache;
            Callback           = callback;
            StreamFragmentSize = 4096;
            DisableRetry       = (methodType == HTTPMethods.Post);
            MaxRedirects       = 2147483647;
            RedirectCount      = 0;
            IsCookiesEnabled   = HTTPManager.IsCookiesEnabled;
            int num3 = Downloaded = (DownloadLength = 0);

            DownloadProgressChanged = false;
            State                           = HTTPRequestStates.Initial;
            ConnectTimeout                  = HTTPManager.ConnectTimeout;
            Timeout                         = HTTPManager.RequestTimeout;
            EnableTimoutForStreaming        = false;
            Proxy                           = HTTPManager.Proxy;
            UseUploadStreamLength           = true;
            DisposeUploadStream             = true;
            CustomCertificateVerifyer       = HTTPManager.DefaultCertificateVerifyer;
            CustomClientCredentialsProvider = HTTPManager.DefaultClientCredentialsProvider;
            UseAlternateSSL                 = HTTPManager.UseAlternateSSLDefaultValue;
        }
Exemple #14
0
 /// <summary>
 /// Tries to find the appropriate HTTPMethod for the given HTTPMethods.
 /// </summary>
 /// <param name="myCode">A HTTPMethod code as string</param>
 /// <returns>A HTTPMethod</returns>
 public static HTTPMethod ParseEnum(HTTPMethods myHTTPMethodsEnum)
 {
     return((from _FieldInfo in typeof(HTTPMethod).GetFields()
             let __HTTPMethod = _FieldInfo.GetValue(null) as HTTPMethod
                                where  __HTTPMethod != null
                                where  __HTTPMethod.MethodName == myHTTPMethodsEnum.ToString()
                                select __HTTPMethod).FirstOrDefault());
 }
        /// <summary>
        /// Generates a new HTTP mapping.
        /// </summary>
        /// <param name="HTTPMethod">The HTTP method of this HTTP mapping.</param>
        /// <param name="UriTemplate">The URI template of this HTTP mapping.</param>
        public HTTPMappingAttribute(HTTPMethods HTTPMethod, String UriTemplate)
        {
            this.HTTPMethod  = de.ahzf.Vanaheimr.Hermod.HTTP.HTTPMethod.ParseEnum(HTTPMethod);

            if (this.HTTPMethod == null)
                throw new ArgumentNullException("Invalid HTTPMethod!");

            this.UriTemplate = UriTemplate;
        }
 private string Send(HTTPMethods method, string relativeUri, StringBuilder headers, string body, string contentType, string accept)
 {
     byte[] bodyBytes = null;
     if (!string.IsNullOrEmpty(body))
     {
         bodyBytes = new UTF8Encoding().GetBytes(body);
     }
     return((string)this.SendBytesArray(relativeUri, headers, bodyBytes, true));
 }
        private object SendBytesArray(string relativeUri, StringBuilder headers, byte[] bodyBytes, bool isSend = false)
        {
            HTTPMethods method     = HTTPMethods.POST;
            var         client     = new HttpClient();
            string      requestUri = string.Format("{0}{1}", EndPoint.AbsolutePath, relativeUri);

            if (isSend)
            {
                requestUri = string.Format("{0}{1}", Address, relativeUri);
            }

            client.BaseAddress = new Uri(requestUri);
            Task <HttpResponseMessage> response = null;

            if (string.IsNullOrEmpty(relativeUri))
            {
                throw new ArgumentException("relativeUri is empty");
            }

            try
            {
                switch (method)
                {
                case HTTPMethods.POST:
                case HTTPMethods.PUT:
                    HttpContent content = new ByteArrayContent(bodyBytes);
                    response = client.PostAsync(requestUri, content);
                    break;
                }
            }
            catch (WebException webException)
            {
                string body = string.Empty;
                try
                {
                    using (var reader2 = new StreamReader(webException.Response.GetResponseStream()))
                    {
                        body = reader2.ReadToEnd();
                    }
                }
                catch
                {
                    body = "Unable to get response";
                }
                throw new InvalidResponseException("Failed: " + body, webException, (response != null) ? response.Result.StatusCode : HttpStatusCode.BadRequest, body);
            }
            catch (Exception exception)
            {
                throw new InvalidResponseException("Failed: " + exception.Message, exception);
            }

            var streamTask = (StreamContent)response.Result.Content;
            var text       = new StreamReader(streamTask.ReadAsStreamAsync().Result);

            text.ReadToEnd();
            return(response.Result);
        }
Exemple #18
0
 public HTTPRequest(string url, HTTPMethods method, Action <HTTPRequest, HTTPResponse> act, int timeout = 60)
 {
     this.act     = act;
     this.request = new UnityWebRequest(url, Methods[method])
     {
         downloadHandler = new DownloadHandlerBuffer(),
         timeout         = timeout,
     };
 }
        public HTTPErrorAttribute(HTTPMethods HTTPMethod, String UriTemplate, HTTPStatusCode myHTTPStatusCode)
        {
            this.HTTPMethod     = org.GraphDefined.Vanaheimr.Hermod.HTTP.HTTPMethod.ParseEnum(HTTPMethod);

            if (this.HTTPMethod == null)
                throw new ArgumentNullException("Invalid HTTPMethod!");

            this.UriTemplate    = UriTemplate;
            this.HTTPStatusCode = myHTTPStatusCode;
        }
Exemple #20
0
        static void Main(string[] args)
        {
            CookieContainer myCookies = new CookieContainer();

            HTTPMethods.Login(ref myCookies);
            string username = "******";

            HTTPMethods.ListOfSolvedProblems(username, myCookies);
            Console.ReadLine();
        }
Exemple #21
0
        /// <summary>
        /// Tries to find the appropriate HTTPMethod for the given HTTPMethods.
        /// </summary>
        /// <param name="HTTPMethodEnum">A HTTP method.</param>
        /// <param name="HTTPMethod">The parsed HTTP method.</param>
        /// <returns>true or false</returns>
        public static Boolean TryParseEnum(HTTPMethods HTTPMethodEnum, out HTTPMethod HTTPMethod)
        {
            HTTPMethod = (from _FieldInfo in typeof(HTTPMethod).GetFields()
                          let __HTTPMethod = _FieldInfo.GetValue(null) as HTTPMethod
                                             where  __HTTPMethod != null
                                             where  __HTTPMethod.MethodName == HTTPMethodEnum.ToString()
                                             select __HTTPMethod).FirstOrDefault();

            return((HTTPMethod != null) ? true : false);
        }
Exemple #22
0
 public void Request(string url,
                     HTTPMethods methods = HTTPMethods.Get,
                     Dictionary <string, string> headers = null,
                     WWWForm param = null,
                     Action <DownloadHandler> onSuccess = null,
                     Action <float> onProgress          = null,
                     Action <DownloadHandler> onError   = null)
 {
     StartCoroutine(RequestSync(url: url, methods: methods, param: param, headers: headers, onSuccess: onSuccess, onProgress: onProgress, onError: onError));
 }
Exemple #23
0
 public static void SendRequest(string endpoint, HTTPMethods method, ApiContainer responseContainer = null, Dictionary <string, object> requestParams = null, bool authenticationRequired = true, bool disableCache = false, float cacheLifetime = 3600f, int retryCount = 2, CredentialsBundle credentials = null)
 {
     if (Logger.DebugLevelIsEnabled(DebugLevel.API))
     {
         Logger.LogFormat(DebugLevel.API, "Requesting {0} {1} {2} disableCache: {3} retryCount: {4}", method, endpoint, (requestParams == null) ? "{{}}" : Json.Encode(requestParams).Replace("{", "{{").Replace("}", "}}"), disableCache.ToString(), retryCount.ToString());
     }
     UpdateDelegator.Dispatch(delegate
     {
         SendRequestInternal(endpoint, method, responseContainer, requestParams, authenticationRequired, disableCache, cacheLifetime, retryCount, credentials);
     });
 }
Exemple #24
0
        /// <summary>
        /// Generates a new HTTP mapping.
        /// </summary>
        /// <param name="HTTPMethod">The HTTP method of this HTTP mapping.</param>
        /// <param name="UriTemplate">The URI template of this HTTP mapping.</param>
        public HTTPMappingAttribute(HTTPMethods HTTPMethod, String UriTemplate)
        {
            this.HTTPMethod = HTTP.HTTPMethod.ParseEnum(HTTPMethod);

            if (this.HTTPMethod == null)
            {
                throw new ArgumentNullException("Invalid HTTPMethod!");
            }

            this.UriTemplate = UriTemplate;
        }
Exemple #25
0
        public HTTPErrorAttribute(HTTPMethods HTTPMethod, String UriTemplate, HTTPStatusCode myHTTPStatusCode)
        {
            this.HTTPMethod = org.GraphDefined.Vanaheimr.Hermod.HTTP.HTTPMethod.ParseEnum(HTTPMethod);

            if (this.HTTPMethod == null)
            {
                throw new ArgumentNullException("Invalid HTTPMethod!");
            }

            this.UriTemplate    = UriTemplate;
            this.HTTPStatusCode = myHTTPStatusCode;
        }
Exemple #26
0
 public HTTPRequest(Uri uri, HTTPMethods methodType, bool isKeepAlive, bool disableCache, Action<HTTPRequest, HTTPResponse> callback)
 {
     Uri = uri;
     MethodType = methodType;
     IsKeepAlive = isKeepAlive;
     DisableCache = disableCache;
     Callback = callback;
     StreamFragmentSize = 4096;
     DisableRetry = (methodType == HTTPMethods.Post);
     MaxRedirects = 2147483647;
     RedirectCount = 0;
 }
Exemple #27
0
    private HTTPRequest RequestCreate(Uri uri, HTTPMethods method, OnRequestFinishedDelegate callback)
    {
        HTTPRequest request = new HTTPRequest(
            uri: uri,
            methodType: method,
            isKeepAlive: true,
            disableCache: true,
            callback: callback
            );

        return(request);
    }
Exemple #28
0
        public async Task <IActionResult> GetOrderList()
        {
            HttpResponseMessage result = await HTTPMethods.Get(_httpApiUrlStrs.Value.BusinessApiUrl + AjaxUrls["GetOrderList"].ToString());

            if (result.StatusCode == System.Net.HttpStatusCode.OK)
            {
                return(SuccessInfo(await result.Content.ReadAsStringAsync()));
            }
            else
            {
                return(Fail("未知错误!"));
            }
        }
Exemple #29
0
        private HTTPRequest RequestCreate(Uri uri, HTTPMethods method, OnRequestFinishedDelegate callback)
        {
            HTTPRequest request = new HTTPRequest(
                uri: uri,
                methodType: method,
                isKeepAlive: true,
                disableCache: true,
                callback: callback
                );

            request.AddHeader("Authorization", this.AccessToken);
            request.AddHeader("UserID", this.UserID);
            return(request);
        }
        public async Task <IActionResult> GetMachineStatisticsList(string process_Id, string variety_Id, DateTime?searchDate)
        {
            try
            {
                string requestUrl = _httpApiUrlStrs.Value.BusinessApiUrl + AjaxUrls["GetMachineStatisticsList"].ToString();
                var    result     = await HTTPMethods.Get(requestUrl);

                return(Success(result));
            }
            catch (Exception e)
            {
                return(Fail("未知错误"));
            }
        }
 /// <summary>
 /// Creates a new HTTP event mapping.
 /// </summary>
 /// <param name="EventIdentification">The internal identification of the HTTP event.</param>
 /// <param name="UriTemplate">The URI template of this HTTP event mapping.</param>
 /// <param name="HTTPMethod">The HTTP method to use.</param>
 /// <param name="MaxNumberOfCachedEvents">Maximum number of cached events (0 means infinite).</param>
 /// <param name="RetryIntervallSeconds">The retry intervall in seconds.</param>
 /// <param name="IsSharedEventSource">The event source may be accessed via multiple URI templates.</param>
 public HTTPEventMappingAttribute(String       EventIdentification,
                                  String       UriTemplate,
                                  HTTPMethods  HTTPMethod,
                                  UInt32       MaxNumberOfCachedEvents  = 0,
                                  UInt64       RetryIntervallSeconds    = 30,
                                  Boolean      IsSharedEventSource      = false)
 {
     this.EventIdentification      = EventIdentification;
     this.UriTemplate              = UriTemplate;
     this.HTTPMethod               = org.GraphDefined.Vanaheimr.Hermod.HTTP.HTTPMethod.ParseEnum(HTTPMethod);
     this.MaxNumberOfCachedEvents  = MaxNumberOfCachedEvents;
     this.RetryIntervall           = TimeSpan.FromSeconds(RetryIntervallSeconds);
     this.IsSharedEventSource      = IsSharedEventSource;
 }
        internal static bool IsCacheble(Uri uri, HTTPMethods method, HTTPResponse response)
        {
            if (!IsSupported)
            {
                return(false);
            }
            if (method != 0)
            {
                return(false);
            }
            if (response == null)
            {
                return(false);
            }
            if (response.StatusCode == 304)
            {
                return(false);
            }
            if (response.StatusCode < 200 || response.StatusCode >= 400)
            {
                return(false);
            }
            List <string> headerValues = response.GetHeaderValues("cache-control");

            if (headerValues != null && headerValues.Exists(delegate(string headerValue)
            {
                string text2 = headerValue.ToLower();
                return(text2.Contains("no-store") || text2.Contains("no-cache"));
            }))
            {
                return(false);
            }
            List <string> headerValues2 = response.GetHeaderValues("pragma");

            if (headerValues2 != null && headerValues2.Exists(delegate(string headerValue)
            {
                string text = headerValue.ToLower();
                return(text.Contains("no-store") || text.Contains("no-cache"));
            }))
            {
                return(false);
            }
            List <string> headerValues3 = response.GetHeaderValues("content-range");

            if (headerValues3 != null)
            {
                return(false);
            }
            return(true);
        }
Exemple #33
0
        /// <summary>
        /// Creates a new HTTP event mapping.
        /// </summary>
        /// <param name="EventIdentification">The internal identification of the HTTP event.</param>
        /// <param name="UriTemplate">The URI template of this HTTP event mapping.</param>
        /// <param name="HTTPMethod">The HTTP method to use.</param>
        /// <param name="MaxNumberOfCachedEvents">Maximum number of cached events (0 means infinite).</param>
        /// <param name="RetryIntervallSeconds">The retry intervall in seconds.</param>
        /// <param name="IsSharedEventSource">The event source may be accessed via multiple URI templates.</param>
        public HTTPEventMappingAttribute(String EventIdentification,
                                         String UriTemplate,
                                         HTTPMethods HTTPMethod,
                                         UInt32 MaxNumberOfCachedEvents = 0,
                                         UInt64 RetryIntervallSeconds   = 30,
                                         Boolean IsSharedEventSource    = false)

        {
            this.EventIdentification     = EventIdentification;
            this.UriTemplate             = UriTemplate;
            this.HTTPMethod              = org.GraphDefined.Vanaheimr.Hermod.HTTP.HTTPMethod.ParseEnum(HTTPMethod);
            this.MaxNumberOfCachedEvents = MaxNumberOfCachedEvents;
            this.RetryIntervall          = TimeSpan.FromSeconds(RetryIntervallSeconds);
            this.IsSharedEventSource     = IsSharedEventSource;
        }
		protected void CreateRequest(string action, Action<HTTPRequest, HTTPResponse> callback, HTTPMethods methodType = HTTPMethods.Get) {
			request = new HTTPRequest (new Uri (_host + action), methodType, (HTTPRequest req, HTTPResponse res) => {
				if (interstitialLoading) {
					_dispatcher.Dispatch("loading_interstitial_close");
				}
				// if finished correctly
				if (req.State == HTTPRequestStates.Finished) {
					ClearError();
					callback(req, res);
				}
				// if not show an error with a retry and/or a go back to main menu
				else {
					Debug.Log (req.State);
					ShowError();
					GameAnalytics.NewErrorEvent (GA_Error.GAErrorSeverity.GAErrorSeverityCritical , "Failed connection: " + PlayerPrefs.GetString("username") + " | " + action + " | " + req.State);
				}
			});
			// add options
			AddOptions ();
		}
        public HTTPRequest(Uri uri, HTTPMethods methodType, bool isKeepAlive, bool disableCache, Action<HTTPRequest, HTTPResponse> callback)
        {
            this.Uri = uri;
            this.MethodType = methodType;
            this.IsKeepAlive = isKeepAlive;
            this.DisableCache = disableCache;
            this.Callback = callback;
            this.StreamFragmentSize = 4 * 1024;

            this.DisableRetry = methodType == HTTPMethods.Post;
            this.MaxRedirects = int.MaxValue;
            this.RedirectCount = 0;
            this.IsCookiesEnabled = HTTPManager.IsCookiesEnabled;

            Downloaded = DownloadLength = 0;
            DownloadProgressChanged = false;

            State = HTTPRequestStates.Initial;

            ConnectTimeout = HTTPManager.ConnectTimeout;
            Timeout = HTTPManager.RequestTimeout;
            EnableTimoutForStreaming = false;
        }
        internal static HTTPCacheFileInfo Store(Uri uri, HTTPMethods method, HTTPResponse response)
        {
            if (response == null || response.Data == null || response.Data.Length == 0)
                return null;

            HTTPCacheFileInfo info = null;

            lock (Library)
            {
                if (!Library.TryGetValue(uri, out info))
                    Library.Add(uri, info = new HTTPCacheFileInfo(uri));

                try
                {
                    info.Store(response);
                }
                catch
                {
                    // If something happens while we write out the response, than we will delete it becouse it might be in an invalid state.
                    DeleteEntity(uri);

                    throw;
                }
            }

            return info;
        }
        /// <summary>
        /// Checks if the given response can be cached. http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.4
        /// </summary>
        /// <returns>Returns true if cacheable, false otherwise.</returns>
        internal static bool IsCacheble(Uri uri, HTTPMethods method, HTTPResponse response)
        {
            if (method != HTTPMethods.Get)
                return false;

            if (response == null)
                return false;

            // Already cached
            if (response.StatusCode == 304)
                return false;

            if (response.StatusCode < 200 || response.StatusCode >= 400)
                return false;

            //http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9.2
            var cacheControls = response.GetHeaderValues("cache-control");
            if (cacheControls != null && cacheControls[0].ToLower().Contains("no-store"))
                return false;

            var pragmas = response.GetHeaderValues("pragma");
            if (pragmas != null && pragmas[0].ToLower().Contains("no-cache"))
                return false;

            // Responses with byte ranges not supported yet.
            var byteRanges = response.GetHeaderValues("content-range");
            if (byteRanges != null)
                return false;

            return true;
        }
 public HTTPRequest(Uri uri, HTTPMethods methodType, bool isKeepAlive, Action<HTTPRequest, HTTPResponse> callback)
     : this(uri, methodType, isKeepAlive, HTTPManager.IsCachingDisabled, callback)
 {
 }
Exemple #39
0
 public static HTTPRequest SendRequest(string url, HTTPMethods methodType, bool isKeepAlive, bool disableCache, OnRequestFinishedDelegate callback)
 {
     return SendRequest(new HTTPRequest(new Uri(url), methodType, isKeepAlive, disableCache, callback));
 }
Exemple #40
0
 public static HTTPRequest SendRequest(string url, HTTPMethods methodType, OnRequestFinishedDelegate callback)
 {
     return SendRequest(new HTTPRequest(new Uri(url), methodType, callback));
 }
 public static HTTPRequest SendRequest(string url, HTTPMethods methodType, Action<HTTPRequest, HTTPResponse> callback)
 {
     return SendRequest(new HTTPRequest(new Uri(url), methodType, callback));
 }
 public static HTTPRequest SendRequest(string url, HTTPMethods methodType, bool isKeepAlive, bool disableCache, Action<HTTPRequest, HTTPResponse> callback)
 {
     return SendRequest(new HTTPRequest(new Uri(url), methodType, isKeepAlive, disableCache, callback));
 }