Exemple #1
0
        public string getResponse(string url, HttpRequestMethod method = HttpRequestMethod.GET, Dictionary<string,string> postData=null, CookieContainer cookies=null)
        {
            string result = "";
            var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
            httpWebRequest.AllowAutoRedirect = true;
            httpWebRequest.AllowWriteStreamBuffering = true;
            httpWebRequest.KeepAlive = true;
            httpWebRequest.Method = method.ToString();

               if(cookies!=null)
            httpWebRequest.CookieContainer = cookies;

               if (method == HttpRequestMethod.POST)
            {
                string queryString = QueryStringHelper.toQueryString(postData);
                byte[] b = System.Text.Encoding.ASCII.GetBytes(queryString);
                httpWebRequest.ContentType = "application/x-www-form-urlencoded";
                httpWebRequest.ContentLength = (long)b.Length;
                Stream httpStream = httpWebRequest.GetRequestStream();
                httpStream.Write(b, 0, b.Length);
                httpStream.Close();

            }

            var objResponse = (HttpWebResponse)httpWebRequest.GetResponse();
            using (var sr = new StreamReader(objResponse.GetResponseStream()))
            {
                result = sr.ReadToEnd();
                sr.Close();
            }
            return result;
        }
Exemple #2
0
        public HttpRequestWrapper(string url, HttpRequestMethod method, Encoding encode)
        {
            reqSetting = new HttpRequestSetting(url, method, encode);
            httpRequest = new HttpRequest();

            cookieParser = new CookieParser();
        }
Exemple #3
0
        /// <summary>
        ///     Builds and configures an <see cref="HttpWebRequest"/> object with the given parameters.
        /// </summary>
        /// <param name="method">HTTP verb to use for the request.</param>
        /// <param name="uri">Address of a local or remote HTTP server.</param>
        /// <param name="cache">Determines whether the request should be cached.</param>
        /// <param name="headers">HTTP request headers to send to the server.</param>
        /// <returns>A fully configured <see cref="HttpWebRequest"/> object.</returns>
        public static HttpWebRequest BuildRequest(HttpRequestMethod method, string uri, bool cache = false, List<string> headers = null)
        {
            LogBuildRequest(method, uri, cache, headers);

            var request = (HttpWebRequest) WebRequest.Create(uri);

            request.Method = method.ToString("G").ToUpper();
            request.UserAgent = UserAgent;
            request.KeepAlive = true;
            request.CachePolicy = new RequestCachePolicy(cache ? RequestCacheLevel.CacheIfAvailable : RequestCacheLevel.BypassCache);
            request.Expect = null;

            if (headers != null && headers.Count > 0)
            {
                foreach (var header in headers)
                {
                    request.Headers.Add(header);
                }
            }

            if (HttpRequestMethod.Post == method || HttpRequestMethod.Put == method)
            {
                request.ContentType = "application/x-www-form-urlencoded";
            }

            return request;
        }
Exemple #4
0
 public RestClient(string link, string contentType = "text/json", HttpRequestMethod method = HttpRequestMethod.GET)
 {
     Link = link;
     Method = method;
     ContentType = contentType;
     _parameters = new Dictionary<string, string>();
     Parameters = new ReadOnlyDictionary<string, string>(_parameters);
 }
Exemple #5
0
 public static void Test_HttpRequest(string url, HttpRequestMethod method, string content, string file)
 {
     file = zPath.Combine(_directory, file);
     bool exportResult = HttpManager.CurrentHttpManager.ExportResult;
     HttpManager.CurrentHttpManager.ExportResult = true;
     HttpRun.LoadToFile(new HttpRequest { Url = url, Method = method, Content = content }, file, true, new HttpRequestParameters { Encoding = Encoding.UTF8 });
     HttpManager.CurrentHttpManager.ExportResult = exportResult;
 }
 /// <param name="url">${WP_mapping_ServiceBase_method_SubmitRequest_param_url_D}</param>
 /// <param name="parameters">${WP_mapping_ServiceBase_method_SubmitRequest_param_parameters_D}</param>
 /// <param name="onCompleted">${WP_mapping_ServiceBase_method_SubmitRequest_param_onCompleted_D}</param>
 /// <param name="state">${WP_mapping_ServiceBase_method_SubmitRequest_param_state_D}</param>
 /// <param name="forcePost">${WP_mapping_ServiceBase_method_SubmitRequest_param_forcePost_D}</param>
 /// <param name="isEditable">${WP_mapping_ServiceBase_method_SubmitRequest_param_isEditable_D}</param>
 /// <param name="isTempLayersSet">${WP_mapping_ServiceBase_method_SubmitRequest_param_isTempLayersSet_D}</param>
 /// <summary>${WP_mapping_ServiceBase_method_SubmitRequest_D}</summary>
 /// <overloads>${WP_mapping_ServiceBase_method_SubmitRequest_overloads_D}</overloads>
 protected async Task<string> SubmitRequest(string url, HttpRequestMethod method,string data)
 {
     request.Url = url;
     request.PostBody = data;
     request.ProxyUrl = ProxyURL;
     request.RequestMethod = method;
     return await request.BeginRequest();
 }
Exemple #7
0
        private void ParseRequestMethod(string[] requestLine)
        {
            HttpRequestMethod parsedMethod;
            string            method            = requestLine[0];
            string            capitalizedMethod = method.Capitalize();

            if (!Enum.TryParse(capitalizedMethod, true, out parsedMethod))
            {
                throw new BadRequestException();
            }

            this.RequestMethod = parsedMethod;
        }
Exemple #8
0
 public Response(
     IHeadersCollection headersCollection,
     int statusCode,
     HttpRequestMethod httpRequestMethod,
     byte[] responseData,
     TResponseBody?body,
     AbsoluteUrl requestUri
     ) : base(
         headersCollection,
         statusCode,
         httpRequestMethod,
         responseData,
         requestUri) => Body = body;
        public bool?Contains(HttpRequestMethod requestMethod, string path)
        {
            CoreValidator.ThrowIfNull(requestMethod, nameof(requestMethod));
            CoreValidator.ThrowIfNullOrEmpty(path, nameof(path));


            if (!this.routes.ContainsKey(requestMethod))
            {
                return(null);
            }

            return(this.routes[requestMethod].ContainsKey(path));
        }
Exemple #10
0
        private void ParseRequestMethod(string[] requestLines)
        {
            HttpRequestMethod httpRequestMethod;

            if (!Enum.TryParse(requestLines[0], true, out httpRequestMethod))
            {
                throw new BadRequestException(
                          string.Format(GlobalConstants.UnsupportedHttpMethodExceptionMethod,
                                        requestLines[0]));
            }

            this.RequestMethod = httpRequestMethod;
        }
Exemple #11
0
        public ServerRouteConfig(IAppRouteConfig appRouteConfig)
        {
            this.Routes = new Dictionary <HttpRequestMethod, Dictionary <string, IRoutingContext> >();

            foreach (int num in Enum.GetValues(typeof(HttpRequestMethod)))
            {
                HttpRequestMethod method = (HttpRequestMethod)num;

                Routes[method] = new Dictionary <string, IRoutingContext>();
            }

            this.InitializeServerConfig(appRouteConfig);
        }
Exemple #12
0
        /// <summary>
        ///     Instantiates a new <see cref="Route"/>.
        /// </summary>
        /// <param name="method"> The HTTP request method. </param>
        /// <param name="path"> The formattable relative path. </param>
        public Route(HttpRequestMethod method, string path)
        {
            Guard.IsDefined(method);
            Guard.IsNotNullOrWhiteSpace(path);

            if (path.StartsWith('/'))
            {
                Throw.FormatException("The path must be a relative path with no leading slash.");
            }

            Method = method;
            Path   = path;
        }
Exemple #13
0
        private void ParseRequestMethod(string[] requestLine)
        {
            HttpRequestMethod method;

            bool result = HttpRequestMethod.TryParse(requestLine[0], true, out method);

            if (!result)
            {
                throw new BadRequestException(String.Format(GlobalConstants.UnsupportedHttpMethodExceptionMessage, requestLine[0]));
            }

            this.RequestMethod = method;
        }
Exemple #14
0
        public static void Test_HttpRequest(string url, HttpRequestMethod method, string content, string file)
        {
            file = zPath.Combine(_directory, file);
            bool exportResult = HttpManager.CurrentHttpManager.ExportResult;

            HttpManager.CurrentHttpManager.ExportResult = true;
            HttpRun_v1.LoadToFile(new HttpRequest {
                Url = url, Method = method, Content = content
            }, file, true, new HttpRequestParameters {
                Encoding = Encoding.UTF8
            });
            HttpManager.CurrentHttpManager.ExportResult = exportResult;
        }
Exemple #15
0
        protected HttpResponse Execute(HttpRequestMethod method, string relativePath, Action <HttpWebRequest> modifyRequest = null, Action <Stream> writeToUpStream = null, Action <HttpWebResponse> handleResponse = null, Action <Stream> readDownStream = null)
        {
            var output = new HttpResponse();

            try {
                var httpRequest = CreateRequest(method, relativePath);

                using (_cancelToken?.Register(() => {
                    httpRequest.Abort();
                })) {
                    modifyRequest?.Invoke(httpRequest);

                    // write to upstream
                    if (writeToUpStream != null)
                    {
                        using (var upStream = httpRequest.GetRequestStream()) {
                            writeToUpStream(upStream);
                        }
                    }

                    // get response
                    using (var httpWebResponse = (HttpWebResponse)httpRequest.GetResponse()) {
                        output.StatusCode        = httpWebResponse.StatusCode;
                        output.StatusDescription = httpWebResponse.StatusDescription;
                        handleResponse?.Invoke(httpWebResponse);

                        // read downstream
                        if (readDownStream != null)
                        {
                            using (var downStream = httpWebResponse.GetResponseStream()) {
                                readDownStream(downStream);
                            }
                        }
                    }
                }
            } catch (Exception e) {
                output.Exception = e;
                if (e is WebException we && we.Response is HttpWebResponse hwr)
                {
                    output.StatusCode        = hwr.StatusCode;
                    output.StatusDescription = hwr.StatusDescription;
                }
            }

            if (!(output.Exception is OperationCanceledException) && (_cancelToken?.IsCancellationRequested ?? false))
            {
                output.Exception = new OperationCanceledException();
            }

            return(output);
        }
Exemple #16
0
        private void ParseRequestMethod(string[] requestLineParams)
        {
            string            methodName = requestLineParams[0];
            HttpRequestMethod requestMethod;

            bool isParsed = Enum.TryParse(methodName, true, out requestMethod);

            if (!isParsed)
            {
                throw new BadRequestException();
            }

            this.RequestMethod = requestMethod;
        }
Exemple #17
0
        public static HttpMethod GetHttpMethod(HttpRequestMethod method)
        {
            switch (method)
            {
            case HttpRequestMethod.Get:
                return(HttpMethod.Get);

            case HttpRequestMethod.Post:
                return(HttpMethod.Post);

            default:
                throw new PBException($"unknow HttpRequestMethod {method}");
            }
        }
Exemple #18
0
        private void ParseRequestMethod(string[] requestLine)
        {
            if (!requestLine.Any())
            {
                throw new BadRequestException();
            }
            var parseResult = System.Enum.TryParse <HttpRequestMethod>(requestLine[0], out var parsedRequestmethod);

            if (!parseResult)
            {
                throw new BadRequestException();
            }
            this.RequestMethod = parsedRequestmethod;
        }
Exemple #19
0
        private void ParseRequestMethod(string[] requestLineParams)
        {
            string            requestMethod = requestLineParams[0];
            HttpRequestMethod method;

            bool parseResult = HttpRequestMethod.TryParse(requestMethod, true, out method);

            if (!parseResult)
            {
                throw new BadRequestException(string.Format(GlobalConstants.UnsupportedHttpMethodExceptionMessage, requestMethod));
            }

            this.RequestMethod = method;
        }
        public IHttpResponse Handle(IHttpContext httpContext)
        {
            try
            {
                string loginPath    = "/login";
                string registerPath = "/register";

                //if (httpContext.Request.Path != loginPath
                //    && httpContext.Request.Path != registerPath
                //    && !httpContext.Request.Session.Containts(CurrentUserSessionKey))
                //{
                //    return new RedirectResponse(loginPath);
                //}

                HttpRequestMethod requestMethod = httpContext.Request.RequestMethod;
                string            requestPath   = httpContext.Request.Path;
                var registeredRoutes            = this.serverRouteConfig.Routes[requestMethod];

                foreach (var registeredRoute in registeredRoutes)
                {
                    string          routePattern   = registeredRoute.Key;
                    IRoutingContext routingContext = registeredRoute.Value;

                    Regex regex = new Regex(routePattern);
                    Match match = regex.Match(requestPath);


                    if (!match.Success)
                    {
                        continue;
                    }

                    var parameters = routingContext.Parameters;

                    foreach (string parameter in parameters)
                    {
                        string parameterValue = match.Groups[parameter].Value;
                        httpContext.Request.AddUrlParameter(parameter, parameterValue);
                    }

                    return(routingContext.RequestHandler.Handle(httpContext));
                }
            }
            catch (Exception ex)
            {
                return(new InternalServerErrorResponse(ex));
            }

            return(new NotFoundResponse());
        }
        public IHttpResponse Handle(IHttpContext context)
        {
            try
            {
                // Check if user is authenticated
                string[] anonymousPaths = new[] { "/login", "/register" };

                if (!anonymousPaths.Contains(context.HttpRequest.Path) &&
                    (context.HttpRequest.Session == null || !context.HttpRequest.Session.Contains(SessionRepository.CurrentUserKey)))
                {
                    return(new RedirectResponse(anonymousPaths.First()));
                }

                HttpRequestMethod requestMethod = context.HttpRequest.RequestMethod;
                string            requestPath   = context.HttpRequest.Path;

                IDictionary <string, IRoutingContext> registeredRoutes = this.serverRouteConfig.Routes[requestMethod];

                foreach (KeyValuePair <string, IRoutingContext> registeredRoute in registeredRoutes)
                {
                    string          routePattern = registeredRoute.Key;
                    IRoutingContext routeContext = registeredRoute.Value;

                    Regex routeRegex = new Regex(routePattern);
                    Match match      = routeRegex.Match(requestPath);

                    if (!match.Success)
                    {
                        continue;
                    }

                    IEnumerable <string> parameters = routeContext.Parameters;

                    foreach (string parameter in parameters)
                    {
                        string parameterValue = match.Groups[parameter].Value;

                        context.HttpRequest.AddUrlParameter(parameter, parameterValue);
                    }

                    return(routeContext.RequestHandler.Handle(context));
                }
            }
            catch (Exception exception)
            {
                return(new InternalServerErrorResponse(exception));
            }

            return(new NotFoundResponse());
        }
        private string HttpMethodToString(HttpRequestMethod httpMethod)
        {
            switch (httpMethod)
            {
            case HttpRequestMethod.HttpMethod_Post:
                return("POST");

            case HttpRequestMethod.HttpMethod_Get:
                return("GET");

            default:
                return("POST");
            }
        }
        private void ResolveRelationDependency(
            object model,
            string requesterID,
            IRequest request,
            IRequest relatedRequest,
            TRelation intractionType,
            HttpRequestMethod httpRequestMethod)
        {
            var propertyList = model.GetType()
                               .GetProperties()
                               .Where(property => property.IsDefined(typeof(RelationDependentValueAttribute), true))
                               .ToList();

            var updateModel = false;

            foreach (var item in propertyList)
            {
                var attribute = item.GetCustomAttribute <RelationDependentValueAttribute> ();

                var relationDependentResolver =
                    httpRequestMethod == HttpRequestMethod.Post ?
                    attribute.OnRelationCreated :
                    attribute.OnReleationDeleted;

                var result = APIUtils.InvokeMethod(
                    relationDependentResolver,
                    "OnRelationEvent",
                    new object[] {
                    dbContext,
                    model,
                    requesterID,
                    request,
                    relatedRequest,
                    intractionType,
                    httpRequestMethod
                });

                if (result != null)
                {
                    model       = result;
                    updateModel = true;
                }
            }

            if (updateModel)
            {
                dbContext.Update(model);
            }
        }
Exemple #24
0
 public dynamic ModelValidation(
     IRequest Request,
     Type ModelType,
     ModelAction ModelAction,
     HttpRequestMethod RequestMethod,
     TRelation RelationType) =>
 GeneralAccessChainValidation(
     Request: Request,
     Type: ModelType,
     ModelAction: ModelAction,
     RequestMethod: RequestMethod,
     RelationType: RelationType,
     ModelItself: null,
     TypeValue: Request.IdentifierValue,
     DefaultPolicy: false);
Exemple #25
0
 public dynamic ModelPropertyValidation(
     IRequest Request,
     PropertyInfo PropertyInfo,
     object Model,
     ModelAction ModelAction,
     HttpRequestMethod RequestMethod) =>
 GeneralAccessChainValidation(
     Request: Request,
     Type: PropertyInfo,
     ModelAction: ModelAction,
     RequestMethod: RequestMethod,
     RelationType: default(TRelation),
     TypeValue: PropertyInfo.GetValue(Model),
     ModelItself: Model,
     DefaultPolicy: true);
Exemple #26
0
        /// <summary>
        ///     Instantiates a new <see cref="Route"/>.
        /// </summary>
        /// <param name="method"> The HTTP request method. </param>
        /// <param name="path"> The formattable relative path. </param>
        public Route(HttpRequestMethod method, string path)
        {
            if (string.IsNullOrWhiteSpace(path))
            {
                throw new ArgumentNullException(nameof(path));
            }

            if (path.StartsWith('/'))
            {
                throw new FormatException("The path must be a relative path with no leading slash.");
            }

            Method = method;
            Path   = path;
        }
Exemple #27
0
        public static string GetMethodString(this HttpRequestMethod method)
        {
            switch (method)
            {
            case HttpRequestMethod.Get: return("get");

            case HttpRequestMethod.Post: return("post");

            case HttpRequestMethod.Put: return("put");

            case HttpRequestMethod.Delete: return("delete");

            default: return(method.ToString());
            }
        }
Exemple #28
0
        /// <summary>
        /// Initializes a new instance of the <see cref="HttpSensorParameters"/> class.
        /// </summary>
        /// <param name="url">The URL to monitor.</param>
        /// <param name="sensorName">The name to use for this sensor.</param>
        /// <param name="requestMethod">The HTTP request method to use.</param>
        /// <param name="timeout">The duration (in seconds) this sensor can run for before timing out. This value must be between 1-900.</param>
        /// <param name="postData">Data to include in requests when the HTTP request method is <see cref="PrtgAPI.HttpRequestMethod.POST"/>.</param>
        /// <param name="useCustomPostContent">Whether to use a custom content type in POST requests.</param>
        /// <param name="postContentType">The custom content type to use in POST requests.</param>
        /// <param name="useSNIFromUrl">Whether the Server Name Indication should be derived from the specified <see cref="Url"/>, or from the parent device.</param>
        public HttpSensorParameters(string url      = "http://", string sensorName    = "HTTP", HttpRequestMethod requestMethod = HttpRequestMethod.GET, int timeout = 60,
                                    string postData = null, bool useCustomPostContent = false, string postContentType           = null, bool useSNIFromUrl           = false) : base(sensorName, SensorType.Http)
        {
            Url = url;
            HttpRequestMethod    = requestMethod;
            Timeout              = timeout;
            PostData             = postData;
            UseCustomPostContent = useCustomPostContent;
            PostContentType      = postContentType;
            UseSNIFromUrl        = useSNIFromUrl;

            //todo: add a unit test for this to our existing test files that test on wmi service/exexml sensors
            //update about_sensorsettings to document the new objectproperty types
            //make a note to update wiki to say this type is now nataively supported
        }
Exemple #29
0
        private static void AutoRegisterRoutes(IMvcApplication application,
                                               IServerRoutingTable serverRoutingTable,
                                               IServiceProvider serviceProvider,
                                               RouteSettings routeSettings)
        {
            IEnumerable <System.Type> controllers = application.GetType().Assembly
                                                    .GetTypes()
                                                    .Where(type => type.IsClass && !type.IsAbstract && typeof(Controller).IsAssignableFrom(type));

            foreach (var controllerType in controllers)
            {
                IEnumerable <MethodInfo> actions = controllerType.GetMethods(BindingFlags.DeclaredOnly |
                                                                             BindingFlags.Instance | BindingFlags.Public)
                                                   .Where(m => !m.IsSpecialName && !m.IsVirtual && m.GetCustomAttribute <NonActionAttribute>() == null);

                string controllerName = controllerType.Name.Replace("Controller", "");

                AuthorizeAttribute controllerAuthorizeAttribute = controllerType.GetCustomAttribute <AuthorizeAttribute>() as AuthorizeAttribute;

                foreach (var action in actions)
                {
                    string path = $"/{controllerName}/{action.Name}";

                    BaseHttpAttribute attribute = action.GetCustomAttributes()
                                                  .LastOrDefault(a => a.GetType().IsSubclassOf(typeof(BaseHttpAttribute))) as BaseHttpAttribute;

                    HttpRequestMethod requestMethod = HttpRequestMethod.Get;

                    if (attribute != null)
                    {
                        requestMethod = attribute.HttpRequestMethod;
                    }
                    if (attribute?.ActionName != null)
                    {
                        path = $"/{controllerName}/{attribute.ActionName}";
                    }
                    if (attribute?.Url != null)
                    {
                        path = attribute.Url;
                    }

                    serverRoutingTable.Add(requestMethod, path, request =>
                    {
                        return(ProcessRequest(serviceProvider, request, controllerType, controllerAuthorizeAttribute, action, routeSettings));
                    });
                }
            }
        }
 protected Response(
     IHeadersCollection headersCollection,
     int statusCode,
     HttpRequestMethod httpRequestMethod,
     byte[] responseData,
     TResponseBody body,
     Uri requestUri
     ) : base(
         headersCollection,
         statusCode,
         httpRequestMethod,
         responseData,
         requestUri)
 {
     Body = body;
 }
Exemple #31
0
        public static HttpMethod GetMethod(this HttpRequestMethod requestMethod)
        {
            switch (requestMethod)
            {
            case HttpRequestMethod.Get:    return(HttpMethod.Get);

            case HttpRequestMethod.Post:   return(HttpMethod.Post);

            case HttpRequestMethod.Put:    return(HttpMethod.Put);

            case HttpRequestMethod.Delete: return(HttpMethod.Delete);

            default:
                throw new ArgumentOutOfRangeException(nameof(requestMethod));
            }
        }
Exemple #32
0
        private void ParseRequestMethod(string[] requestLine)
        {
            if (!requestLine.Any())
            {
                throw new BadRequestException();
            }

            bool parsed = Enum.TryParse(requestLine[0].Capitalize(), out HttpRequestMethod requestMethod);

            if (!parsed)
            {
                throw new BadRequestException();
            }

            this.RequestMethod = requestMethod;
        }
Exemple #33
0
        private dynamic CreateResource(
            IRequest request,
            HttpRequestMethod requestMethod,
            PermissionHandler <TRelation, TUser> permissionHandler,
            string jsonData)
        {
            var jsonResolver = new APIJsonResolver <TRelation, TUser> {
                DbContext         = dbContext,
                PermissionHandler = permissionHandler,
                ModelAction       = ModelAction.Create,
                RequestMethod     = requestMethod,
                IRequest          = request,
                IncludeKey        = false,
                IncludeBindNever  = false,
                EngineService     = EngineService
            };

            var serializerSettings = JsonConvert.DefaultSettings();

            serializerSettings.ContractResolver = jsonResolver;

            var model =
                JsonConvert.DeserializeObject(
                    value: jsonData,
                    type: request.Temp_ResourceType,
                    settings: serializerSettings);

            dbContext.Add(model);
            dbContext.SaveChanges();

            var intraction = new ModelInteraction <TRelation> {
                CreatorId      = permissionHandler.getRequesterID(),
                FirstModelId   = permissionHandler.getRequesterID(),
                SecondModelId  = model.GetKeyPropertyValue(),
                IntractionType = (TRelation)Enum.Parse(typeof(TRelation), "Global"),
                ModelAction    = ModelAction.Create
            };

            dbContext.MagicAddIntraction(intraction, EngineService.MapRelationToType("Global"));
            dbContext.SaveChangesAsync();

            EngineService.OnResourceCreated(dbContext, request, model, intraction);

            return(new OkObjectResult(new {
                GeneratedID = model.GetKeyPropertyValue()
            }));
        }
Exemple #34
0
        internal static string HttpPost(string url, List<string> parameters, CredentialBase credential, HttpRequestMethod httpRequestMethod)
        {
            url += ".json?";

            parameters = parameters.Where(p => !string.IsNullOrEmpty(p)).ToList();

            url = GenerateUrl(url, parameters);

            HttpWebRequest httpRequest;

            if (credential.GetType() == typeof(Credential.OAuth))
            {
                if (!((Credential.OAuth)credential).HasToken)
                    ((Credential.OAuth)credential).Login();

                httpRequest = HttpPostOAuth(url, (Credential.OAuth)credential, httpRequestMethod);
            }
            else
                httpRequest = HttpPostBasic(url, credential, httpRequestMethod);

            try
            {
                using (var response = (HttpWebResponse)httpRequest.GetResponse())
                using (var reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
                {
                    var result = reader.ReadToEnd();
                    return result;
                }
            }
            catch (WebException ex)
            {
                var result = new StreamReader(ex.Response.GetResponseStream(), Encoding.UTF8).ReadToEnd();
                var error = new JavaScriptSerializer().Deserialize<ErrorObj>(result);

                if (!string.IsNullOrEmpty(error.Error))
                    throw new Exception.WebException(error.Error);

                if (!string.IsNullOrEmpty(error.RateLimited))
                    throw new Exception.RateLimitedException(error.RateLimited);

                if (!string.IsNullOrEmpty(error.Unauthorized))
                    throw new Exception.UnauthorizedException(error.Unauthorized);

                throw;
            }
        }
Exemple #35
0
 /// <summary>
 /// Sends a HTTP Request with the chosen request method
 /// </summary>
 /// <param name="url">Url to send request to</param>
 /// <param name="method">HTTP Request Method to use</param>
 /// <param name="data">Query string data to send</param>
 /// <param name="count">How many times to try the connection before giving up</param>
 public static string SendRequest(string url, HttpRequestMethod method, Dictionary<string, string> data = null, int count = 3)
 {
     // Try sending n times
     for(int i = 0; i < count; i++) {
         switch(method) {
             case HttpRequestMethod.POST:
                 return SendPost(url, GetRequestString(data));
             case HttpRequestMethod.GET:
                 return SendGet(url + "?" + GetRequestString(data));
             case HttpRequestMethod.PUT:
                 return SendPut(url, GetRequestString(data));
             case HttpRequestMethod.DELETE:
                 return SendDelete(url);
         }
     }
     throw new Exception("Request failed to send. Unknown error. Please check the parameters for errors.");
 }
 public SerializeValueProvider(
     IValueProvider ValueProvider,
     PermissionHandler <TRelation, TUser> PermissionHandler,
     IRequest IRequest,
     TRelation Relation,
     PropertyInfo PropertyType,
     ModelAction modelAction,
     HttpRequestMethod requestMethod)
 {
     this.ValueProvider     = ValueProvider;
     this.PermissionHandler = PermissionHandler;
     this.IRequest          = IRequest;
     this.PropertyType      = PropertyType;
     this.ModelAction       = modelAction;
     this.RequestMethod     = requestMethod;
     this.Relation          = Relation;
 }
Exemple #37
0
        private void ParseRequestMethod(string[] requestLine)
        {
            if (!requestLine.Any())
            {
                throw new BadRequestException();
            }

            string reqMethod         = requestLine[0];
            bool   tryParseReqMethod = Enum.TryParse(reqMethod, true, out HttpRequestMethod method);

            if (!tryParseReqMethod)
            {
                throw new BadRequestException();
            }

            this.RequestMethod = method;
        }
Exemple #38
0
 public void RequestAsync(HttpRequestMethod method, byte[] data, OnRESTResponse onRequest, params string[] headers)
 {
     Worker.WorkerDelegate onWork = delegate(out object result)
     {
         Request(method, data, null, headers);
         result = null;
         return(true);
     };
     Worker.WorkerFinishedDelegate onFinish = delegate(Exception e, object result)
     {
         //if (e != null)
         //    throw e;
         //onRequest?.Invoke(m_error == null, m_error == null ? null : m_error.ToString(), m_stream);
         onRequest?.Invoke(m_error == null, m_error == null ? null : m_error.ToString(), m_stream);
     };
     Worker.StartWorker(onWork, onFinish);
 }
        /// <summary>
        /// Get an instance of a request class
        /// </summary>
        /// <returns>
        /// The instance
        /// </returns>
        /// <param name="method">
        /// The method that the request class should implement
        /// </param>
        /// <exception cref="NotSupportedException">
        /// Thrown if the given method has yet to be supported.
        /// </exception>
        public static EasyHttpRequest GetInstance(HttpRequestMethod method)
        {
            switch (method)
            {
                case HttpRequestMethod.Post:
                {
                    return new PostEasyHttpRequest();
                }

                case HttpRequestMethod.Get:
                {
                    return new GetEasyHttpRequest();
                }

                default:
                {
                    throw new NotSupportedException(String.Format("The HttpRequestMethod '{0}' is not supported yet", method));
                }
            }
        }
 public static HttpStatusCode PerformRequest(HttpRequestMethod method, string urlPath)
 {
     return PerformRequest(method, urlPath, null, null, null);
 }
        protected virtual HttpStatusCode PerformRequest(HttpRequestMethod method, string urlPath,
            WriteXmlDelegate writeXmlDelegate, ReadXmlDelegate readXmlDelegate, ReadXmlListDelegate readXmlListDelegate)
        {
            var url = Settings.GetServerUri(urlPath);
            #if (DEBUG)
            Console.WriteLine("Requesting " + method + " " + url);
            #endif
            var request = (HttpWebRequest)WebRequest.Create(url);
            request.Accept = "application/xml";      // Tells the server to return XML instead of HTML
            request.ContentType = "application/xml; charset=utf-8"; // The request is an XML document
            request.SendChunked = false;             // Send it all as one request
            request.UserAgent = Settings.UserAgent;
            request.Headers.Add(HttpRequestHeader.Authorization, Settings.AuthorizationHeaderValue);
            request.Method = method.ToString().ToUpper();

            Debug.WriteLine(String.Format("Recurly: Requesting {0} {1}", request.Method, request.RequestUri));

            if ((method == HttpRequestMethod.Post || method == HttpRequestMethod.Put) && (writeXmlDelegate != null))
            {
                // 60 second timeout -- some payment gateways (e.g. PayPal) can take a while to respond
                request.Timeout = 60000;

                // Write POST/PUT body
                using (var requestStream = request.GetRequestStream())
                {
                    WritePostParameters(requestStream, writeXmlDelegate);
                }
            }
            else
            {
                request.ContentLength = 0;
            }

            try
            {
                using (var response = (HttpWebResponse)request.GetResponse())
                {

                    ReadWebResponse(response, readXmlDelegate, readXmlListDelegate);
                    return response.StatusCode;

                }
            }
            catch (WebException ex)
            {
                if (ex.Response == null) throw;

                var response = (HttpWebResponse)ex.Response;
                var statusCode = response.StatusCode;
                Error[] errors;

                Debug.WriteLine(String.Format("Recurly Library Received: {0} - {1}", (int)statusCode, statusCode));

                switch (response.StatusCode)
                {
                    case HttpStatusCode.OK:
                    case HttpStatusCode.Accepted:
                    case HttpStatusCode.Created:
                    case HttpStatusCode.NoContent:
                        ReadWebResponse(response, readXmlDelegate, readXmlListDelegate);

                        return HttpStatusCode.NoContent;

                    case HttpStatusCode.NotFound:
                        errors = Error.ReadResponseAndParseErrors(response);
                        if (errors.Length > 0)
                            throw new NotFoundException(errors[0].Message, errors);
                        throw new NotFoundException("The requested object was not found.", errors);

                    case HttpStatusCode.Unauthorized:
                    case HttpStatusCode.Forbidden:
                        errors = Error.ReadResponseAndParseErrors(response);
                        throw new InvalidCredentialsException(errors);

                    case HttpStatusCode.PreconditionFailed:
                        errors = Error.ReadResponseAndParseErrors(response);
                        throw new ValidationException(errors);

                    case HttpStatusCode.ServiceUnavailable:
                        throw new TemporarilyUnavailableException();

                    case HttpStatusCode.InternalServerError:
                        errors = Error.ReadResponseAndParseErrors(response);
                        throw new ServerException(errors);
                }

                if ((int)statusCode == ValidationException.HttpStatusCode) // Unprocessable Entity
                {
                    errors = Error.ReadResponseAndParseErrors(response);
                    if (errors.Length > 0) Debug.WriteLine(errors[0].ToString());
                    else Debug.WriteLine("Client Error: " + response.ToString());
                    throw new ValidationException(errors);
                }

                throw;
            }
        }
 public HttpStatusCode PerformRequest(HttpRequestMethod method, string urlPath,
     ReadXmlListDelegate readXmlListDelegate)
 {
     return PerformRequest(method, urlPath, null, null, readXmlListDelegate);
 }
 public HttpStatusCode PerformRequest(HttpRequestMethod method, string urlPath,
     WriteXmlDelegate writeXmlDelegate, ReadXmlDelegate readXmlDelegate)
 {
     return PerformRequest(method, urlPath, writeXmlDelegate, readXmlDelegate, null);
 }
Exemple #44
0
 public static string SendRequest(string url, HttpRequestMethod method, int count = 3)
 {
     Exception ex = null;
     for(int i = 0; i < count; i++) //Try sending 3 Times
     {
         var request = GetJsonRequest(url, method);
         try {
             var response = (HttpWebResponse)request.GetResponse();
             if(response.StatusCode == HttpStatusCode.OK || response.StatusCode == HttpStatusCode.Created) {
                 using(var stream = new StreamReader(response.GetResponseStream()))
                     return stream.ReadToEnd();
             }
             else if(response.StatusCode == HttpStatusCode.InternalServerError)
                 count--;
         }
         catch(Exception e) {
             ex = e;
         }
     }
     throw ex;
 }
        public static HttpStatusCode PerformRequest(HttpRequestMethod method, string urlPath,
            Action<XmlTextWriter> writeXmlDelegate, Action<XmlTextReader> readXmlDelegate, Action<WebHeaderCollection> headersDelegate)
        {
            var url = urlPath.Contains("http") ? urlPath : ServerUrl + urlPath;
            var request = (HttpWebRequest)WebRequest.Create(url);
            request.Accept = "application/xml";      // Tells the server to return XML instead of HTML
            request.SendChunked = false;             // Send it all as one request
            request.UserAgent = UserAgent;
            request.Headers.Add(HttpRequestHeader.Authorization, AuthorizationHeaderValue);
            request.Method = method.ToString().ToUpper();

            System.Diagnostics.Debug.WriteLine("Recurly: Requesting {0} {1}",
                request.Method, request.RequestUri);

            if (method == HttpRequestMethod.Post || method == HttpRequestMethod.Put)
            {
                request.ContentLength = 0;
                // 60 second timeout -- some payment gateways (e.g. PayPal) can take a while to respond
                request.Timeout = 60000;

                if(writeXmlDelegate != null)
                {
                    request.ContentType = "application/xml; charset=utf-8"; // The request is an XML document
                    // Write POST/PUT body
                    using (var ms = new MemoryStream())
                    {
                        WritePostParameters(ms, writeXmlDelegate);

                        var bytes = ms.ToArray();

                        System.Diagnostics.Debug.WriteLine("Recurly Body: {0}{1}",Environment.NewLine,Encoding.UTF8.GetString(bytes));

                        request.ContentLength = bytes.Length;
                        request.GetRequestStream().Write(bytes, 0, bytes.Length);
                    }
                }
            }

            try
            {
                using (var response = (HttpWebResponse)request.GetResponse())
                    return ReadWebResponse(response, readXmlDelegate, headersDelegate);
            }
            catch (WebException ex)
            {
                if (ex.Response != null)
                {
                    var response = (HttpWebResponse)ex.Response;
                    var statusCode = response.StatusCode;
                    List<RecurlyError> errors;

                    System.Diagnostics.Debug.WriteLine("Recurly Library Received: {0} - {1}",
                                                       (int) statusCode, statusCode);

                    switch (response.StatusCode)
                    {
                        case HttpStatusCode.OK:
                        case HttpStatusCode.Accepted:
                        case HttpStatusCode.Created:
                        case HttpStatusCode.NoContent:
                            return ReadWebResponse(response, readXmlDelegate, headersDelegate);

                        case HttpStatusCode.NotFound:
                            //return response.StatusCode;
                            errors = RecurlyError.ReadResponseAndParseErrors(response);
                            if (errors.Any())
                                throw new NotFoundException(errors[0].Symbol, errors);
                            throw new NotFoundException("The requested object was not found.", errors);

                        case HttpStatusCode.Unauthorized:
                        case HttpStatusCode.Forbidden:
                            errors = RecurlyError.ReadResponseAndParseErrors(response);
                            throw new InvalidCredentialsException(errors);

                        case HttpStatusCode.PreconditionFailed:
                            errors = RecurlyError.ReadResponseAndParseErrors(response);
                            throw new ValidationException(errors);

                        case HttpStatusCode.ServiceUnavailable:
                            throw new TemporarilyUnavailableException();

                        case HttpStatusCode.InternalServerError:
                            errors = RecurlyError.ReadResponseAndParseErrors(response);
                            throw new RecurlyServerException(errors);
                    }

                    if ((int)statusCode == ValidationException.HttpStatusCode) // Unprocessable Entity
                    {
                        errors = RecurlyError.ReadResponseAndParseErrors(response);
                        throw new ValidationException(errors);
                    }
                }

                throw;
            }
        }
        public static HttpStatusCode PerformRequest(HttpRequestMethod method, string urlPath,
            WriteXmlDelegate writeXmlDelegate, ReadXmlDelegate readXmlDelegate)
        {
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(ServerUrl(Environment) + urlPath);
            request.Accept = "application/xml";      // Tells the server to return XML instead of HTML
            request.ContentType = "application/xml"; // The request is an XML document
            request.SendChunked = false;             // Send it all as one request
            request.UserAgent = UserAgent;
            request.Headers.Add(HttpRequestHeader.Authorization, AuthorizationHeaderValue);
            request.Method = method.ToString().ToUpper();

            System.Diagnostics.Debug.WriteLine(String.Format("Recurly: Requesting {0} {1}",
                request.Method, request.RequestUri.ToString()));

            if ((method == HttpRequestMethod.Post || method == HttpRequestMethod.Put) && (writeXmlDelegate != null))
            {
                // 60 second timeout -- some payment gateways (e.g. PayPal) can take a while to respond
                request.Timeout = 60000;

                // Write POST/PUT body
                using (Stream requestStream = request.GetRequestStream())
                    WritePostParameters(requestStream, writeXmlDelegate);
            }

            try
            {
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                return ReadWebResponse(response, readXmlDelegate);
            }
            catch (WebException ex)
            {
                if (ex.Response != null)
                {
                    HttpWebResponse response = (HttpWebResponse)ex.Response;
                    HttpStatusCode statusCode = response.StatusCode;
                    RecurlyError[] errors;

                    System.Diagnostics.Debug.WriteLine(String.Format("Recurly Library Received: {0} - {1}",
                        (int)statusCode, statusCode.ToString()));

                    switch (response.StatusCode)
                    {
                        case HttpStatusCode.OK:
                        case HttpStatusCode.Accepted:
                        case HttpStatusCode.Created:
                        case HttpStatusCode.NoContent:
                            return ReadWebResponse(response, readXmlDelegate);

                        case HttpStatusCode.NotFound:
                            errors = RecurlyError.ReadResponseAndParseErrors(response);
                            if (errors.Length >= 0)
                                throw new NotFoundException(errors[0].Message, errors);
                            else
                                throw new NotFoundException("The requested object was not found.", errors);

                        case HttpStatusCode.Unauthorized:
                        case HttpStatusCode.Forbidden:
                            errors = RecurlyError.ReadResponseAndParseErrors(response);
                            throw new InvalidCredentialsException(errors);

                        case HttpStatusCode.PreconditionFailed:
                            errors = RecurlyError.ReadResponseAndParseErrors(response);
                            throw new ValidationException(errors);

                        case HttpStatusCode.ServiceUnavailable:
                            throw new TemporarilyUnavailableException();

                        case HttpStatusCode.InternalServerError:
                            errors = RecurlyError.ReadResponseAndParseErrors(response);
                            throw new RecurlyServerException(errors);
                    }

                    if ((int)statusCode == ValidationException.HttpStatusCode) // Unprocessable Entity
                    {
                        errors = RecurlyError.ReadResponseAndParseErrors(response);
                        throw new ValidationException(errors);
                    }
                }

                throw;
            }
        }
Exemple #47
0
        /// <summary>
        /// 根据给定地址和请求类型获取内容
        /// </summary>
        /// <param name="url">请求地址(可直接带参数)</param>
        /// <param name="method">请求方法</param>
        /// <param name="type">请求内容类型</param>
        /// <param name="content">请求内容(不需要就不传)</param>
        /// <returns></returns>
        public static string GetHttpResponse(string url, HttpRequestMethod method = HttpRequestMethod.GET, HttpRequestContentType type = HttpRequestContentType.Default, string content = null)
        {
            // 创建 WebRequest 对象,WebRequest 是抽象类,定义了规范
            // HttpWebRequest 是 WebRequest 的派生类,专门用于 HTTP 请求
            var request = (HttpWebRequest)HttpWebRequest.Create(url);

            // 请求的方式通过 Method 属性设置 ,默认为 GET
            // 可以将 Method 属性设置为任何 HTTP 1.1 协议谓词:GET、HEAD、POST、PUT、DELETE、TRACE 或 OPTIONS。
            switch (method)
            {
                case HttpRequestMethod.POST:
                    request.Method = "POST";
                    break;
                case HttpRequestMethod.GET:
                default:
                    request.Method = "GET";
                    break;
            }

            // 设置请求的内容类型
            switch (type)
            {
                case HttpRequestContentType.UrlEncoded:
                    request.ContentType = "application/x-www-form-urlencoded";
                    content = HttpContext.Current.Server.UrlEncode(content);
                    break;
                case HttpRequestContentType.Json:
                    request.ContentType = "application/json";
                    break;
                case HttpRequestContentType.Default:
                default:
                    //request.ContentType = "text/plain";
                    break;
            }

            // 如果有请求内容的话,写入请求流中
            if (!string.IsNullOrWhiteSpace(content))
            {
                // 取得发向服务器的流
                using (var requestStream = request.GetRequestStream())
                {
                    // 使用 POST 方法请求的时候,实际的参数通过请求的 Body 部分以流的形式传送
                    using (var writer = new StreamWriter(requestStream))
                    {
                        writer.Write(content);
                    }

                    // 设置请求参数的长度.
                    request.ContentLength = requestStream.Length;
                }
            }

            #region Cookies暂不需要

            // 还可以在请求中附带 Cookie
            // 但是,必须首先创建 Cookie 容器

            //request.CookieContainer = new CookieContainer();

            //var requestCookie = new System.Net.Cookie("Request", "RequestValue", "/", "localhost");
            //request.CookieContainer.Add(requestCookie);

            #endregion

            HttpWebResponse response;
            try
            {
                // GetResponse 方法才真的发送请求,等待服务器返回
                response = (HttpWebResponse)request.GetResponse();
            }
            catch (WebException ex)
            {
                response = ex.Response as HttpWebResponse;
                SignalRHelper.SendMessageToChatRoom("HTTP请求异常", response == null ? ex.Message : response.StatusDescription);
            }

            // 对请求结果的处理
            if (response != null)
            {
                // 请求成功得到以流的形式表示的回应内容
                using (var responseStream = response.GetResponseStream())
                {
                    if (responseStream != null)
                    {
                        string result;

                        //读取返回内容
                        using (var reader = new StreamReader(responseStream))
                        {
                            result = reader.ReadToEnd();
                        }

                        return result;
                    }
                }
            }
            return string.Empty;
        }
Exemple #48
0
 public bool LoadToFile(string path, string url, HttpRequestMethod method, string content)
 {
     return LoadToFile(path, url, method, content, null);
 }
Exemple #49
0
 private static void LogBuildRequest(HttpRequestMethod method, string uri, bool cache = false, List<string> headers = null)
 {
     var strHeaders = "";
     if (headers != null && headers.Count > 0)
     {
         strHeaders = string.Format(" with headers: {0}", string.Join("; ", headers));
     }
     Logger.DebugFormat("{0} \"{1}\" -- cache = {2}{3}", method.ToString("G").ToUpper(), uri, cache, strHeaders);
 }
Exemple #50
0
        public void ResetParameters()
        {
            if (gbResult)
            {
                gMethod = HttpRequestMethod.Get;
                //gsAccept = null;
                gsReferer = null;
                //gAutomaticDecompression = null;
                gHeaders = new NameValueCollection();
                gsRequestContentType = null;
                gsContent = null;
                //gEncoding = null;
                //gbUseWebClient = false;
                //giLoadXmlRetryTimeout = 0;
                //gsTraceDirectory = null;
                gsTextExportPath = null;
                //gbReadCommentInText = false;

                gsTextResult = null;
                gsContentType = null;
                gsCharset = null;

                gbResult = false;
            }
        }
 public static HttpStatusCode PerformRequest(HttpRequestMethod method, string urlPath,
     Action<XmlTextReader> readXmlDelegate, Action<WebHeaderCollection> headersDelegate)
 {
     return PerformRequest(method, urlPath, null, readXmlDelegate, headersDelegate);
 }
Exemple #52
0
 public static void DownLoad(string path, string url, HttpRequestMethod method, string content, string referer)
 {
     Http http = new Http();
     http.LoadToFile(path, url, method, content, referer);
 }
 public static HttpStatusCode PerformRequest(HttpRequestMethod method, string urlPath,
     Action<XmlTextWriter> writeXmlDelegate, Action<XmlTextReader> readXmlDelegate)
 {
     return PerformRequest(method, urlPath, writeXmlDelegate, readXmlDelegate, null);
 }
Exemple #54
0
 public static string LoadText(string url, HttpRequestMethod method, string content)
 {
     return LoadText(url, method, content, null);
 }
Exemple #55
0
 public static string LoadText(string url, HttpRequestMethod method, string content, string referer)
 {
     Http http = new Http();
     http.Load(url, method, content, referer);
     return http.TextResult;
 }
Exemple #56
0
 public void Load(string url, HttpRequestMethod method, string content, string referer)
 {
     Reset();
     gsUrl = GetUrl(gsUrl, url);
     gMethod = method;
     gsContent = content;
     gsReferer = referer;
     Load();
 }
Exemple #57
0
 public static void DownLoad(string path, string url, HttpRequestMethod method, string content)
 {
     DownLoad(path, url, method, content, null);
 }
Exemple #58
0
        static WebRequest GetJsonRequest(string url, HttpRequestMethod method)
        {
            var request = WebRequest.Create(url);

            request.Method = Enum.GetName(typeof(HttpRequestMethod), method).ToUpper();
            request.ContentType = "application/json";
            request.ContentLength = 0;

            return request;
        }
Exemple #59
0
 public bool LoadToFile(string path, string url, HttpRequestMethod method, string content, string referer)
 {
     Reset();
     gsUrl = GetUrl(gsUrl, url);
     gMethod = method;
     gsContent = content;
     gsReferer = referer;
     return LoadToFile(path);
 }
Exemple #60
0
        private static string PutOrPost(HttpRequestMethod method, string uri, IDictionary<string, string> formData)
        {
            var request = BuildRequest(method, uri);

            using (var requestStream = request.GetRequestStream())
            {
                using (var streamWriter = new StreamWriter(requestStream))
                {
                    var body = new List<string>();
                    if (formData != null)
                    {
                        body.AddRange(formData.Keys.Select(key => EncodeForPostBody(key, formData[key])));
                    }
                    streamWriter.Write(string.Join("&", body) + "\n");
                    streamWriter.Flush();
                    streamWriter.Close();
                }
            }

            NotifyBeforeRequest(request);

            using (var httpResponse = request.GetResponse())
            {
                using (var responseStream = httpResponse.GetResponseStream())
                {
                    if (responseStream == null)
                    {
                        return null;
                    }
                    using (var streamReader = new StreamReader(responseStream))
                    {
                        var responseText = streamReader.ReadToEnd();
                        return responseText;
                    }
                }
            }
        }