public RestMethodAttribute(string url, RequestMethod method = RequestMethod.Get, string accept = null, string contentType = null)
 {
     this.Url = url;
     this.Method = method;
     this.Accept = accept;
     this.ContentType = contentType;
 }
Esempio n. 2
0
        public static byte[] ExecuteUrl(string url, RequestMethod method = RequestMethod.Post, NameValueCollection Parameters = null)
        {
            using (var webClient = new WebClient())
            {
                try
                {

                    if (RequestMethod.Post == method)
                    {
                        var resBytes = webClient.UploadValues(url, Parameters);
                        return resBytes;
                    }
                    else
                    {
                        var resBytes = webClient.DownloadData(url);
                        return resBytes;
                    }

                }
                catch (Exception e)
                {

                    return null;
                }
            }
        }
        public static RequestInfo Create(
            RequestMethod method, string target, string uriTemplate, Dictionary<string, object> parameters,
            string userAgent, Dictionary<string, string> headers, ContentType requestContentType,
            ContentType responseContentType, TimeSpan cacheDuration,
            int timeout, int retryCount,
            Uri uri, string requestBody, IRequestFactory requestFactory)
        {
            var result = new RequestInfo
                             {
                                 Target = target,
                                 UriTemplate = uriTemplate,
                                 AllowedRetries = retryCount,
                                 Uri = uri,
                                 Method = method,
                                 UserAgent = userAgent,
                                 _headers = new Dictionary<string, string>(headers ?? new Dictionary<string, string>()),
                                 RequestBody = requestBody,
                                 Parameters = new Dictionary<string, object>(parameters ?? new Dictionary<string, object>()),
                                 CacheDuration = cacheDuration,
                                 RequestContentType = requestContentType,
                                 ResponseContentType = responseContentType,
                                 Timeout = timeout
                             };

            return result;
        }
Esempio n. 4
0
        public string PrepareRequestData(object parameters, RequestMethod method)
        {
            var result = string.Empty;

            if (parameters == null)
            {
                return result;
            }

            if (method == RequestMethod.Post)
            {
                switch (ContentType)
                {
                    case ContentType.Json:
                        return JsonConvert.SerializeObject(parameters);

                    case ContentType.Xml:
                        using (var sw = new System.IO.StringWriter())
                        {
                            var serializer = new XmlSerializer(parameters.GetType());
                            serializer.Serialize(sw, this);
                            return sw.ToString();
                        }
                }
            }

            result = ((Dictionary<string, object>)parameters).Aggregate(
                result,
                (current, parameter) => current + (parameter.Key + '=' + parameter.Value.ToString() + '&'));

            return result.Trim(new[] {'&'});
        }
Esempio n. 5
0
        private HttpWebResponse GetResponseFromWattRequest(Uri requestUrl, RequestMethod method, string postData = "")
        {
            try
            {
                var httpWebRequest = (HttpWebRequest)WebRequest.Create(requestUrl);

                httpWebRequest.Credentials = CredentialCache.DefaultCredentials;
                httpWebRequest.CookieContainer = _cookieJar;
                httpWebRequest.UserAgent = "CSharp HTTP Sample";
                httpWebRequest.KeepAlive = true;
                httpWebRequest.Headers.Set("Pragma", "no-cache");
                httpWebRequest.Timeout = 300000;
                httpWebRequest.Method = method.ToString();
                if (method == RequestMethod.Post)
                {
                    httpWebRequest.ContentType = "application/x-www-form-urlencoded";
                    byte[] bytes = Encoding.ASCII.GetBytes(postData);
                    httpWebRequest.ContentLength = bytes.Length;
                    Stream requestStream = httpWebRequest.GetRequestStream();
                    requestStream.Write(bytes, 0, bytes.Length);
                    requestStream.Close();
                }
                return (HttpWebResponse)httpWebRequest.GetResponse();
            }
            catch
            {
                return null;
            }
        }
Esempio n. 6
0
 /// <summary>
 /// Creates the HTTP json request.
 /// </summary>
 /// <param name="self">The self.</param>
 /// <param name="url">The URL.</param>
 /// <param name="method">The method.</param>
 /// <param name="metadata">The metadata.</param>
 /// <param name="credentials">The credentials.</param>
 /// <returns></returns>
 public static HttpJsonRequest CreateHttpJsonRequest(object self, Uri url, RequestMethod method, JObject metadata,
                                                     ICredentials credentials)
 {
     var request = new HttpJsonRequest(url, method, metadata, credentials);
     ConfigureRequest(self, new WebRequestEventArgs {Request = request.webRequest});
     return request;
 }
        public static Method Map(RequestMethod method)
        {
            Method mthd;
            Enum.TryParse(method.ToString().ToUpperInvariant(), out mthd);

            return mthd;
        }
Esempio n. 8
0
 public Request()
 {
     this.contentLength = 0;
     this.contentType = MimeType.Default;
     this.cookies = new CookieCollection();
     this.hasEntityBody = false;
     this.headers = new HeaderCollection();
     this.isAuthenticated = false;
     this.isLocal = false;
     this.isSecureConnection = false;
     this.keepAlive = false;
     this.localEndPoint = null;
     this.method = RequestMethod.Unknown;
     this.protocolType = null;
     this.protocolVersion = null;
     this.rawMethod = null;
     this.rawRequest = null;
     this.rawUrl = null;
     this.referrer = null;
     this.remoteEndPoint = null;
     this.requestData = new RequestDataCollection();
     this.url = null;
     this.userAgent = null;
     this.userHostName = null;
 }
Esempio n. 9
0
 public WebRequestWrapper(Uri uri, RequestMethod requestMethod, string contentType, ref CookieContainer cookieJar, string dataToPost = null)
 {
     this.Uri = uri;
     this.RequestMeth = requestMethod;
     this.ContentType = contentType;
     this.CookieJar = cookieJar;
     this.DataToPost = dataToPost;
 }
 public PollServiceEventArgs(RequestMethod pRequest, HasEventsMethod pHasEvents, GetEventsMethod pGetEvents, NoEventsMethod pNoEvents,UUID pId)
 {
     Request = pRequest;
     HasEvents = pHasEvents;
     GetEvents = pGetEvents;
     NoEvents = pNoEvents;
     Id = pId;
 }
Esempio n. 11
0
 public HtmlForm(RequestMethod method, string action, IDictionary<string, string> errors = null)
     : base("form", null)
 {
     SetAttribut("name", "form");
     SetAttribut("method", method.ToString());
     SetAttribut("action", action);
     SetAttribut("onsubmit", "return FormIsValid()");
     _errors = errors;
 }
Esempio n. 12
0
        public BoxRequest(RequestMethod method, Uri hostUri, string path)
        {
            Method = method;
            Host = hostUri;
            Path = path;

            HttpHeaders = new List<KeyValuePair<string, string>>();
            Parameters = new Dictionary<string, string>();
        }
Esempio n. 13
0
        public RequestSetting(RequestMethod method, string url)
        {
            _protocolVersion = HttpVersion.Version11;
            _method = method;
            _url = url;

            _accept = "text/html,application/xhtml+xml,*/*";
            _userAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/6.0)";
        }
        public Stream Execute(string uri, NameValueCollection data, Dictionary<string, Stream> files, RequestMethod method = RequestMethod.POST)
        {
            String boundary = "SMSAPI-" + DateTime.Now.ToString("yyyy-MM-dd_HH:mm:ss") + (new Random()).Next(int.MinValue, int.MaxValue).ToString() + "-boundary";

            WebRequest webRequest = WebRequest.Create(baseUrl + uri);
            webRequest.Method = RequestMethodToString(method);

            if (basicAuthentication != null)
            {
                webRequest.Headers.Add("Authorization", "Basic " + System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(basicAuthentication.GetUsername() + ":" + basicAuthentication.GetPassword())));
            }

            if (RequestMethod.POST.Equals(method) || RequestMethod.PUT.Equals(method))
            {
                Stream stream;

                if (files != null && files.Count > 0)
                {
                    webRequest.ContentType = "multipart/form-data; boundary=" + boundary;
                    stream = PrepareMultipartContent(boundary, data, files);
                }
                else
                {
                    webRequest.ContentType = "application/x-www-form-urlencoded";
                    stream = PrepareContent(data);
                }

                webRequest.ContentLength = stream.Length;

                try
                {
                    stream.Position = 0;
                    CopyStream(stream, webRequest.GetRequestStream());
                    stream.Close();
                }
                catch (System.Net.WebException e)
                {
                    throw new ProxyException(e.Message, e);
                }
            }

            MemoryStream response = new MemoryStream();

            try
            {
                CopyStream(webRequest.GetResponse().GetResponseStream(), response);
            }
            catch (System.Net.WebException e)
            {
                throw new ProxyException("Failed to get response from " + webRequest.RequestUri.ToString(), e);
            }

            response.Position = 0;
            return response;
        }
Esempio n. 15
0
        private bool ParseRequestLine()
        {
            string[] RequestLineDel = new string[] {" "};
            string[] splittedRequestLine = splittedRequest[0].Split(RequestLineDel, StringSplitOptions.None);

            string methodCheck = splittedRequestLine[0];
            if (methodCheck == "GET")
            {
                this.method = RequestMethod.GET;
            }

            if (methodCheck == "POST")
            {
                this.method = RequestMethod.POST;
            }


            if (methodCheck == "HEAD")
            {
                this.method = RequestMethod.HEAD;
            }


            string version = splittedRequestLine[2];
            if (version == "HTTP/1.0")
            {
                this.httpVersion = HTTPVersion.HTTP10;
            }

            else if (version == "HTTP/1.1")
            {
                this.httpVersion = HTTPVersion.HTTP11;

            }

            else 
            {
                this.httpVersion = HTTPVersion.HTTP09;
            }

            relativeURI = splittedRequestLine[1];
            bool URI = ValidateIsURI(relativeURI);
            if (URI == true)
            {
                return true;
            }
            else
            {
                return false;
            }

            
         //   throw new NotImplementedException();
        }
 public string RequestMethodToString(RequestMethod m)
 {
     switch(m)
     {
         case RequestMethod.rmGet: return "GET";
         case RequestMethod.rmPut: return "PUT";
         case RequestMethod.rmDelete: return "DELETE";
         default:
             throw new Exception(string.Format("Request method {0} not recognized", m));
     }
 }
Esempio n. 17
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="requestUri"></param>
        /// <param name="method"></param>
        /// <param name="request"></param>
        protected void CreateContext(Uri requestUri, RequestMethod method, out HttpJsonRequest request)
        {
            Guard.Assert(() => requestUri != null);

            var metadata = new JObject();

            request = HttpJsonRequest.CreateHttpJsonRequest(this, new Uri(requestUri.AbsoluteUri + Guid.NewGuid()),
                                                            method, metadata, Credentials);

            ContextStorage.Add(request, SynchronizationContext.Current);
        }
Esempio n. 18
0
 private void AddEditRoute(string name, RequestMethod method, string path, bool isAsync, bool isSigned, int editIndex)
 {
     if (name.Length > 0 && path.Length > 0) {
         if (editIndex == -1) {
             // Add the route
             this.routes.Add (new Route (name, method, path, isAsync, isSigned));
         } else {
             // Replace existing route
             this.routes [editIndex] = new Route (name, method, path, isAsync, isSigned);
         }
     }
 }
Esempio n. 19
0
        /// <summary>
        ///     Method is invoked when the application needs to communicate to 
        ///     the server.
        /// </summary>
        /// <param name="method">The type of http call being sent to the server.</param>
        /// <param name="requestUrl">The command being sent to the server.</param>
        /// <param name="json">The parameters being sent to the server.</param>
        /// <returns>The response from the server as a string.</returns>

        public static async Task<string> GetDataV2WithJson(RequestMethod method, string requestUrl, string json)
        {
            //var authKeys = new Dictionary<string, string> { { "key", App.ApiKey }, { "id", BryxHelper.GetUniqueId() } };
            //var authHeader = BryxHelper.EncodeTo64(JsonConvert.SerializeObject(authKeys, Formatting.None));

            var httpClient = new HttpClient(new HttpClientHandler());
            HttpResponseMessage response;
            switch (method)
            {
                case RequestMethod.Post:
                    if (!requestUrl.Contains("authorization"))
                    {
                        httpClient.DefaultRequestHeaders.Add("X-Auth-Token", authHeader);
                    }
                    response = await httpClient.PostAsync(requestUrl, new StringContent(json));
                    if (response.IsSuccessStatusCode == false)
                    {
                        throw new HttpRequestException(((int)response.StatusCode).ToString());
                    }
                    break;
                case RequestMethod.Put:
                    httpClient.DefaultRequestHeaders.Add("X-Auth-Token", authHeader);
                    response =
                        await httpClient.PutAsync(requestUrl, new StringContent(json));
                    if (response.IsSuccessStatusCode == false)
                    {
                        throw new HttpRequestException(((int)response.StatusCode).ToString());
                    }
                    break;
                case RequestMethod.Get:
                    httpClient.DefaultRequestHeaders.Add("X-Auth-Token", authHeader);
                    response =
                        await httpClient.GetAsync(requestUrl);
                    if (response.IsSuccessStatusCode == false)
                    {
                        throw new HttpRequestException(((int)response.StatusCode).ToString());
                    }
                    break;
                case RequestMethod.Delete:
                    httpClient.DefaultRequestHeaders.Add("X-Auth-Token", authHeader);
                    var req = new HttpRequestMessage(HttpMethod.Delete, requestUrl);
                    req.Content = new StringContent(json);
                    response = await httpClient.SendAsync(req);
                    if (response.IsSuccessStatusCode == false)
                    {
                        throw new HttpRequestException(((int)response.StatusCode).ToString());
                    }
                    break;
                default:
                    throw new ArgumentOutOfRangeException(nameof(method), method, null);
            }
            return await response.Content.ReadAsStringAsync();
        }
Esempio n. 20
0
 internal static RequestMethod PureRequestMethod(RequestMethod method)
 {
     switch (method)
     {
         case RequestMethod.ACL_GET:
             return RequestMethod.GET;
         case RequestMethod.ACL_SET:
             return RequestMethod.PUT;
         default:
             return method;
     }
 }
Esempio n. 21
0
        public TusHttpRequest(
            string url,
            RequestMethod method,
            byte[] bodyBytes = null,
            CancellationToken?cancelToken = null)
        {
            Url         = new Uri(url);
            Method      = method.ToString().ToUpperInvariant();
            BodyBytes   = bodyBytes ?? Array.Empty <byte>();
            CancelToken = cancelToken ?? CancellationToken.None;

            _headers.Add(TusHeaderNames.TusResumable, "1.0.0");
        }
Esempio n. 22
0
        public async Task <BaseResponse <TRes, TState> > CallAsync <TRes, TState>(RequestMethod requestMethod, string domain, Tuple <string, string>[] dataParameters, Tuple <string, string>[] urlParameters, params Tuple <string, string>[] headers)
        {
            HttpResponseMessage response;

            CreateHttpClient(requestMethod, domain, dataParameters, urlParameters, out HttpClient client, out HttpRequestMessage requestMessage);

            response = await client.SendAsync(requestMessage).ConfigureAwait(false);

            response.EnsureSuccessStatusCode();


            return(await DeserializeJsonResponse <BaseResponse <TRes, TState> >(response).ConfigureAwait(true));
        }
Esempio n. 23
0
        private Response <TResult> SendRequest <TContent, TResult>(RequestMethod method, TContent content, Func <TResult> resultFactory, CancellationToken cancellationToken, params string[] path)
            where TContent : Model
            where TResult : Model
        {
            using (Request request = CreateRequest(method, path))
            {
                request.Content = HttpPipelineRequestContent.Create(content.Serialize());

                Response response = SendRequest(request, cancellationToken);

                return(CreateResponse(response, resultFactory()));
            }
        }
        /// <summary>
        /// Get an object of <typeparamref name="T"/> from API when expected data should be standard wrapped with extra data on API side.
        /// </summary>
        /// <typeparam name="T">Type of expected object.</typeparam>
        /// <param name="endpoint">API resource endpoint.</param>
        /// <param name="method">Request method.</param>
        /// <param name="body">Request body.</param>
        /// <param name="query">Object for request query.</param>
        /// <param name="dateFormat">Request date format.</param>
        /// <param name="wrappedError"><c>true</c> if possible API exception should be wrapped with extra data on API side, <see cref="ApiResponse{T}"/>; otherwise, <c>false</c>.</param>
        /// <returns>Result of request execution.</returns>
        public virtual ApiResult <T> ExecuteApiWithWrappedResponse <T>(
            string endpoint,
            RequestMethod method,
            object body       = null,
            object query      = null,
            string dateFormat = null,
            bool wrappedError = true)
            where T : class
        {
            var restWrappedResponse = GetRestResponse <ApiResponse <T> >(endpoint, method, body, query, dateFormat);

            return(CreateApiResult <T, ApiResponse <T>, T>(restWrappedResponse, wrappedError));
        }
Esempio n. 25
0
        public async Task <TResponse> RequestAsyncWithCredential <TResponse>(RequestMethod requestMethod, string url, AESRequestBaseModel param, string apiUsername, string apiPassword)
        {
            var handler = new TimeoutHandler
            {
                DefaultTimeout = TimeSpan.FromSeconds(Utils.API_REQUEST_TIMEOUT),
                InnerHandler   = new HttpClientHandler()
                {
                    Credentials = new System.Net.NetworkCredential(apiUsername, apiPassword)
                }
            };

            return(await ExcuteMe <TResponse>(requestMethod, url, param, handler, null));
        }
Esempio n. 26
0
        /// <summary>
        /// creates HttpWebRequest including IDataBase data, request params, query filter and granularity
        /// </summary>
        /// <param name="requestMethod">RequestMethod</param>
        /// <param name="model">Ataxo.SlimAPIClient.Entities.Constants.Model</param>
        /// <param name="requestParams">params od model usually used for updating</param>
        /// <param name="queryItems">filter params</param>
        /// <param name="granularity">Granularity</param>
        /// <returns></returns>
        protected HttpWebRequest CreateRequest(RequestMethod requestMethod, string model, string additional_concretization = null, IDictionary <string, object> requestParams = null, IEnumerable <QueryItem> queryItems = null, Granularity granularity = null)
        {
            string url = ConstrucUrl(PropertiesData, model, additional_concretization, queryItems, granularity);
            Uri    uri = new Uri(url);

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

            request.ContentType          = "application/json";
            request.Headers["Api-Token"] = PropertiesData.AccessToken;
            request.Method = requestMethod.ToString().ToUpper();

            return(request);
        }
Esempio n. 27
0
 protected Request(Session session, RequestMethod method)
 {
     if (session == null)
     {
         throw new ArgumentException("Must have valid session", nameof(session));
     }
     Locale  = "en_US";
     Method  = method;
     Session = session;
     UrlData = new WebRequestHeaders(
         new WebRequestHeader("alt", "json"),
         new WebRequestHeader("hl", Locale));
 }
Esempio n. 28
0
        private bool ParseRequestLine()
        {
            //throw new NotImplementedException();
            string [] req_line;
            string[]  uri;
            req_line = splitRequestString[0].Split(' ');

            if (req_line[0].ToLower() == "get")
            {
                this.method = RequestMethod.GET;
            }
            else if (req_line[0].ToLower() == "head")
            {
                this.method = RequestMethod.HEAD;
            }
            else if (req_line[0].ToLower() == "post")
            {
                this.method = RequestMethod.POST;
            }
            else
            {
                return(false);
            }

            uri = req_line[1].Split('/');
            this.relativeURI = uri[1];

            if (ValidateIsURI(req_line[1]) != true)
            {
                return(false);
            }

            if (req_line[2].ToLower() == "http/0.9")
            {
                this.httpVersion = HTTPVersion.HTTP09;
            }
            else if (req_line[2].ToLower() == "http/1.0")
            {
                this.httpVersion = HTTPVersion.HTTP10;
            }
            else if (req_line[2].ToLower() == "http/1.1")
            {
                this.httpVersion = HTTPVersion.HTTP11;
            }
            else
            {
                return(false);
            }

            return(true);
        }
Esempio n. 29
0
        /// <summary>
        /// 请求数据
        /// </summary>
        /// <param name="body">请求参数Body中的数据</param>
        /// <param name="method">请求方法</param>
        /// <returns>bool 是否成功</returns>
        public Result <T> request(RequestMethod method, object body)
        {
            while (true)
            {
                var helper  = Setting.tokenHelper;
                var request = new HttpRequest(Setting.gateway + url, helper.accessToken);
                if (request.send(method, body))
                {
                    var result = Util.deserialize <Result <T> >(request.data);
                    if (result == null)
                    {
                        return(new Result <T>().serverError($"Response data:{request.data}"));
                    }

                    if (result.success)
                    {
                        return(result);
                    }

                    switch (result.code)
                    {
                    case 422 when !helper.refresTokens():
                        return(result);

                    case 422:
                        continue;

                    case 421 when !helper.getTokens():
                        return(result);

                    case 421:
                        continue;

                    default:
                        if (showError)
                        {
                            Messages.showError(result.message);
                        }

                        return(result);
                    }
                }

                if (showError)
                {
                    Messages.showError(request.message);
                }

                return(new Result <T>().badRequest(request.message));
            }
        }
Esempio n. 30
0
        private string Http(string command, RequestMethod method, params WeiboParameter[] parameters)
        {
            var url = string.Empty;

            if (command.StartsWith("http://") || command.StartsWith("https://"))
            {
                url = command;
            }
            else
            {
                url = string.Format("{0}{1}.json", BASE_URL, command);
            }
            return(OAuth.Request(url, method, parameters));
        }
Esempio n. 31
0
        public bool HandleRequest(RequestMethod method, HttpRequestEventArgs args, Authentication authentication)
        {
            //Prepare the values
            var req = args.Request;
            var res = args.Response;

            //Keep it alive
            res.KeepAlive = true;

            //Make sure we can handle
            if (!CanHandleRequest(req))
            {
                return(false);
            }

            //Make sure its valid type
            bool   requiresContentType = method != RequestMethod.Get && method != RequestMethod.Delete;
            string contentType         = (req.ContentType ?? "application/json").Split(';')[0].Trim();

            if (requiresContentType && contentType != ContentType.JSON && contentType != ContentType.FormUrlEncoded)
            {
                Logger.LogError("BAD REQUEST: Invalid content type");
                res.WriteRest(new RestResponse(RestStatus.BadRequest, msg: $"Invalid content type. Expected '{ContentType.JSON}' or '{ContentType.FormUrlEncoded}' but got '{contentType}'"));
                return(true);
            }

            //Make sure get doesnt have payloads
            if (req.HasEntityBody && (method == RequestMethod.Get || method == RequestMethod.Delete))
            {
                Logger.LogError("BAD REQUEST: Cannot send body with GET or DELETE");
                res.WriteRest(new RestResponse(RestStatus.BadRequest, method.ToString() + " does not support body data."));
                return(true);
            }

            //Load payload
            string body = null;

            if (req.HasEntityBody)
            {
                byte[] buffer = new byte[BUFFER_SIZE];
                int    len    = req.InputStream.Read(buffer, 0, BUFFER_SIZE);
                body = req.ContentEncoding.GetString(buffer, 0, len);
            }

            //Get the response and write it back
            var response = ExecuteRestRequest(method, req.Url.LocalPath, new Query(req), body, authentication, contentType: contentType);

            res.WriteRest(response);
            return(true);
        }
Esempio n. 32
0
        private static HttpWebRequest CreateWebRequest(string url, RequestMethod requestMethod)
        {
            var request = (HttpWebRequest)WebRequest.Create(url);

            request.Method = requestMethod.ToCode();

            if (request.Proxy != null)
            {
                request.UseDefaultCredentials = true;
                request.Proxy = new WebProxy();
            }

            return(request);
        }
//		/// <summary>
//		/// Submit a web request using OAuth, asynchronously.
//		/// </summary>
//		/// <param name="method">GET or POST.</param>
//		/// <param name="url">The full URL, including the query string.</param>
//		/// <param name="postData">Data to post (query string format), if POST methods.</param>
//		/// <param name="callback">The callback to call with the web request data when the asynchronous web request finishes.</param>
//		/// <returns>The return value of QueueUserWorkItem.</returns>
//		public bool AsyncWebRequest (RequestMethod method, string url, string postData, Action<string> callback)
//		{
//			return ThreadPool.QueueUserWorkItem (new WaitCallback (delegate {
//				callback (WebRequest (method, url, postData));
//			}));
//		}

        /// <summary>
        /// Submit a web request using OAuth.
        /// </summary>
        /// <param name="method">GET or POST.</param>
        /// <param name="url">The full URL, including the query string.</param>
        /// <param name="postData">Data to post (query string format), if POST methods.</param>
        /// <returns>The web server response.</returns>
        private string WebRequest(RequestMethod method, string url, string postData)
        {
            Uri uri = new Uri(url);

            var nonce     = GenerateNonce();
            var timeStamp = GenerateTimeStamp();

            Logger.Debug("Building web request for URL: {0}", url);
            if (Debugging)
            {
                Logger.Debug("Generated nonce is {0}", nonce);
                Logger.Debug("Generated time stamp is {0}", timeStamp);
            }

            var outUrl = string.Empty;
            List <IQueryParameter <string> > parameters = null;

            string callbackUrl = string.Empty;

            if (url.StartsWith(RequestTokenBaseUrl) || url.StartsWith(AccessTokenBaseUrl))
            {
                callbackUrl = CallbackUrl;
            }
            var sig = GenerateSignature(uri, ConsumerKey, ConsumerSecret, Token, TokenSecret, Verifier, method,
                                        timeStamp, nonce, callbackUrl, out outUrl, out parameters);

            if (Debugging)
            {
                Logger.Debug("Generated signature {0}", sig);
            }

            parameters.Add(new QueryParameter <string> ("oauth_signature",
                                                        HttpUtility.UrlEncode(sig),
                                                        s => string.IsNullOrEmpty(s)));
            parameters.Sort();

            if (Debugging)
            {
                Logger.Debug("Post data: {0}", postData);
            }

            var ret = MakeWebRequest(method, url, parameters, postData);

            if (Debugging)
            {
                Logger.Debug("Returned value from web request: {0}", ret);
            }

            return(ret);
        }
Esempio n. 34
0
        protected static string RequestApi(Uri uri, string json, RequestMethod method /*, out HttpStatusCode stCode*/)
        {
            var             request = (HttpWebRequest)WebRequest.Create(uri);
            CredentialCache cc      = new CredentialCache();

            cc.Add(uri, "NTLM", CredentialCache.DefaultNetworkCredentials);
            request.Credentials = cc;
            request.ContentType = "text/json";

            switch (method)
            {
            case RequestMethod.Get:
                request.Method = "GET";
                break;

            case RequestMethod.Head:
                request.Method = "HEAD";
                break;

            case RequestMethod.Post:
                request.Method = "POST";
                break;

            case RequestMethod.Put:
                request.Method = "PUT";
                break;

            case RequestMethod.Delete:
                request.Method = "DELETE";
                break;
            }

            using (var streamWriter = new StreamWriter(request.GetRequestStream()))
            {
                streamWriter.Write(json);
                streamWriter.Flush();
                streamWriter.Close();
            }
            string result   = String.Empty;
            var    response = (HttpWebResponse)request.GetResponse();

            using (Stream responseStream = response.GetResponseStream())
            {
                StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
                result = reader.ReadToEnd();
            }
            //stCode = response.StatusCode;
            return(result);
            //return response.StatusCode == HttpStatusCode.Created;
        }
Esempio n. 35
0
        private bool ParseRequestLine() // Done
        {
            this.contentLines = this.requestString.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
            if (this.contentLines.Length < 4)
            {
                return(false);
            }
            else
            {
                this.requestLines = this.contentLines[0].Split(' ');
                if (this.requestLines.Length != 3)
                {
                    return(false);
                }
                switch (this.requestLines[0])
                {
                case "GET":
                    method = RequestMethod.GET;
                    break;

                case "POST":
                    method = RequestMethod.POST;
                    break;

                default:
                    method = RequestMethod.HEAD;
                    break;
                }
                if (!this.ValidateIsURI(this.requestLines[1]))
                {
                    return(false);
                }
                this.relativeURI = this.requestLines[1].Remove(0, 1);
                switch (this.requestLines[2])
                {
                case "HTTP/1.1":
                    this.httpVersion = HTTPVersion.HTTP11;
                    break;

                case "HTTP/1.0":
                    this.httpVersion = HTTPVersion.HTTP10;
                    break;

                default:
                    this.httpVersion = HTTPVersion.HTTP09;
                    break;
                }
            }
            return(true);
        }
Esempio n. 36
0
        public static async Task<string> GetDataV2(RequestMethod method, string command, Dictionary<string, string> reqParams)
        {
            string json;

            if (reqParams != null && (reqParams.ContainsValue("True") || reqParams.ContainsValue("False")))
            {
                json = JsonConvert.SerializeObject(BoolDictionary(reqParams), Formatting.None);
            }
            else
            {
                json = JsonConvert.SerializeObject(reqParams, Formatting.None);
            }
            return await GetDataV2WithJson(method, command, json);
        }
Esempio n. 37
0
        public void Run()
        {
            string command = reader.ReadLine();

            while (command != "ILIENCI")
            {
                string[]      tokens        = command.Split();
                RequestMethod requestMethod = (RequestMethod)Enum.Parse(typeof(RequestMethod), tokens[0]);
                string        uri           = tokens[1];
                string        result        = dispatcher.Dispatch(requestMethod, uri);
                this.writer.WriteLine(result);
                command = reader.ReadLine();
            }
        }
Esempio n. 38
0
        private bool ParseRequestLine()
        {
            if (requestLines.Length != 3)
            {
                return(false);
            }
            if (requestLines[0] == "GET")
            {
                method = RequestMethod.GET;
            }
            else if (requestLines[0] == "POST")
            {
                method = RequestMethod.POST;
            }
            else if (requestLines[0] == "HEAD")
            {
                method = RequestMethod.HEAD;
            }
            else
            {
                return(false);
            }
            if (requestLines[2] == " HTTP/1.0")
            {
                httpVersion = HTTPVersion.HTTP10;
            }
            else if (requestLines[2] == "HTTP/1.1")
            {
                httpVersion = HTTPVersion.HTTP11;
            }
            else if (requestLines[2] == "HTTP/0.9")
            {
                httpVersion = HTTPVersion.HTTP09;
            }
            else
            {
                return(false);
            }
            //if (ValidateIsURI(relativeURI) == false)
            if (ValidateIsURI(requestLines[1]) == false)
            {
                return(false);
            }
            else
            {
                relativeURI = requestLines[1];
            }

            return(true);
        }
Esempio n. 39
0
        private FormUrlEncodedContent GetRequestData <Tpar>(RequestMethod method, Tpar pars)
        {
            var parsSerialized = JsonConvert.SerializeObject(pars);
            var values         = new Dictionary <string, string>
            {
                { "token", _token },
                { "method", method.ToString() },
                { "parameters", parsSerialized }
            };

            var content = new FormUrlEncodedContent(values);

            return(content);
        }
Esempio n. 40
0
        /// <summary>
        /// Создает запрос HttpWebRequest.
        /// </summary>
        /// <param name="token">Ключ авторизации.</param>
        /// <param name="methodType">Метод протокола HTTP.</param>
        /// <param name="method">Метод текущего модуля.</param>
        /// <param name="format">Формат возвращаемых данных.</param>
        /// <returns>Объект HttpWebRequest.</returns>
        public HttpWebRequest CreateRequest(string token, RequestMethod methodType, string method, string format = "json")
        {
            string url = getMethodUrl(method, format);

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

            request.Timeout     = 60 * 1000;
            request.Method      = methodType.ToString();
            request.ContentType = DefaultContentType;

            request.Headers.Add(AuthorizationHeaderName, $"Basic { token }");

            return(request);
        }
Esempio n. 41
0
        public string RequestMethodToString(RequestMethod m)
        {
            switch (m)
            {
            case RequestMethod.rmGet: return("GET");

            case RequestMethod.rmPut: return("PUT");

            case RequestMethod.rmDelete: return("DELETE");

            default:
                throw new Exception(string.Format("Request method {0} not recognized", m));
            }
        }
Esempio n. 42
0
        /// <summary>
        /// Performs an OAuthed api call with the specified access token
        /// </summary>
        /// <param name="apiUrl"></param>
        /// <param name="parameters"></param>
        /// <param name="accessToken"></param>
        /// <returns></returns>
        /// <exception cref="InvalidOperationException">Thrown when no token manager has been specified</exception>
        public ExtApiCallResult ExecuteOAuthApiCall(string apiUrl, IList<ApiParameter> parameters, RequestMethod method,
                                                    string consumerKey, string consumerSecret, string accessToken, string tokenSecret)
        {
            var client = new RestClient(apiUrl);
            client.Authenticator = OAuth1Authenticator.ForAccessToken(consumerKey, consumerSecret, accessToken, tokenSecret);
            var request = new RestRequest();
            request.Method = ConvertRequestMethod(method);

            foreach (var param in parameters)
                request.Parameters.Add(new Parameter { Name = param.Name, Value = param.UnencodedValue, Type = ParameterType.GetOrPost });

            // Execute the request
            return CreateExtApiCallResult(client.Execute(request));
        }
        public BinderByRequest(object InputObject, HttpRequest request, RequestMethod method = RequestMethod.get)
        {
            Request = request;
            BindedObject = InputObject;
            if (method == RequestMethod.post)
            {
                Collections = Request.Form;
            }
            else
            {
                Collections = Request.QueryString;
            }

        }
Esempio n. 44
0
		private async Task<HttpWebRequest> CreateRequest( string api, RequestMethod method, object data, bool authorize )
		{
			var request = (HttpWebRequest)HttpWebRequest.Create( api );
			request.Accept = ApplicationJson;
			request.Timeout = ConnectionTimeout;

			switch( method )
			{
				case RequestMethod.Get:
					request.Method = WebRequestMethods.Http.Get;
					break;
				case RequestMethod.Post:
					request.Method = WebRequestMethods.Http.Post;
					break;
				case RequestMethod.Put:
					request.Method = WebRequestMethods.Http.Put;
					break;
				case RequestMethod.Delete:
					request.Method = "DELETE";
					break;
				default:
					throw new NotSupportedException( String.Format( "Request method {0} not supported", method.ToString() ) );
			}

			if( authorize )
			{
				request.Headers.Add( HttpRequestHeader.Authorization, _serviceKey );
			}

			try
			{
				if( data != null )
				{
					request.ContentType = ApplicationJson;

					using( var outputStream = await request.GetRequestStreamAsync() )
					using( var textWriter = new StreamWriter( outputStream ) )
					using( var jsonWriter = new JsonTextWriter( textWriter ) )
					{
						GetJsonSerializer().Serialize( jsonWriter, data );
					}
				}
			}
			catch( WebException exc )
			{
				throw new WebException( "Error with request " + request.RequestUri, exc );
			}

			return request;
		}
Esempio n. 45
0
        public static IAASResponse Reauest(

            string url,

            RequestMethod method,

            string user,

            string password,

            string sendData)
        {
            return(Request(url, method, user, password, sendData, 20000));
        }
Esempio n. 46
0
        private static string FormatRequestMethod(RequestMethod method)
        {
            switch (method)
            {
            case RequestMethod.POST: return("POST");

            case RequestMethod.GET: return("GET");

            case RequestMethod.DELETE: return("DELETE");

            default:
                throw new SeleniumException("Method not supported {0}", method);
            }
        }
Esempio n. 47
0
        private static async Task <Subscription> Subscription(
            EventType eventType,
            RequestMethod requestMethod = RequestMethod.POST,
            string?targetUrl            = null)
        {
            Subscription subscribed = await BaseTest.Client.Hooks(new Params {
                Action        = Action.subscribe,
                EventType     = eventType,
                RequestMethod = requestMethod,
                TargetUrl     = targetUrl ?? TestHelper.CreateRandomUrl()
            });

            return(subscribed);
        }
Esempio n. 48
0
 public RepresentationType(RequestMethod method, string contentType, string accept)
 {
     if (method == RequestMethod.Post || method == RequestMethod.Put)
     {
         // must have a body, and therefore a content type
         if (contentType == null || contentType == string.Empty)
         {
             throw new ArgumentNullException("contentType", "Cannot create a RepresentationType for POST/PUT without specifying Content-Type");
         }
     }
     Method      = method;
     Accept      = accept;
     ContentType = contentType;
 }
Esempio n. 49
0
        private bool ParseRequestLine()
        {
            //throw new NotImplementedException();

            if (requestLines[0] == "GET")
            {
                method = RequestMethod.GET;
            }
            else if (requestLines[0] == "HEAD")
            {
                method = RequestMethod.HEAD;
            }
            else if (requestLines[0] == "POST")
            {
                method = RequestMethod.POST;
            }
            else
            {
                return(false);
            }

            bool valid_URI = ValidateIsURI(requestLines[1]);

            if (valid_URI == false)
            {
                return(false);
            }
            else
            {
                relativeURI = requestLines[1];
            }

            if (requestLines[2] == "HTTP/1.0")
            {
                httpVersion = HTTPVersion.HTTP10;
            }
            else if (requestLines[2] == "HTTP/1.1")
            {
                httpVersion = HTTPVersion.HTTP11;
            }
            else if (requestLines[2] == "HTTP/0.9" || requestLines[2] == "HTTP")
            {
                httpVersion = HTTPVersion.HTTP09;
            }
            else
            {
                return(false);
            }
            return(true);
        }
Esempio n. 50
0
        /// <summary>
        /// Get Authentication header text
        /// </summary>
        protected string GetHeader(string uri, RequestMethod method, IEnumerable <KeyValuePair <string, string> > param, string pin = null, bool gettingRequestToken = false)
        {
            var oap = GetOAuthParams(
                ConsumerKey, Token,
                GetTimestamp(), GetNonce(),
                SignatureMethod, pin, gettingRequestToken);
            var sig = GetSignature(
                new Uri(uri), ConsumerSecret, Secret,
                JoinParamAsUrl(param == null ? oap : oap.Concat(param)),
                SignatureMethod, method.ToString());

            return(JoinParamAsHeader(
                       oap.Concat(new[] { new KeyValuePair <string, string>(SignatureKey, sig) }).ToArray()));
        }
Esempio n. 51
0
        private static HttpWebRequest CreateHttpRequest(RequestMethod method, string uri, string data, string contentType)
        {
            HttpWebRequest request = null;

            switch (method)
            {
            case RequestMethod.Get:
                request = CreateHttpGetRequest(uri, data, contentType); break;

            case RequestMethod.Post:
                request = CreateHttpPostRequest(uri, data, contentType); break;
            }
            return(request);
        }
Esempio n. 52
0
        /// <summary>
        /// Internal constructor that creates an <see cref="HttpRequest"/> object
        /// </summary>
        /// <param name="method">The underlying Http method.</param>
        /// <param name="URL">The URL of the server.</param>
        /// <param name="content">The request content to be sent to the server.</param>
        /// <param name="contentType">The mimetype of the encapsulated data.</param>
        /// <param name="acceptsType">The type that the client accepts or would prefer to receive. Can be ignored by the server.</param>
        /// <param name="userAgent">Generally used to identfy a requesting device or browser. Can simulate a specific environment.</param>
        internal HttpRequest(RequestMethod method, string URL, HttpContent content, string contentType, string acceptsType, string userAgent)
        {
            //always necessary
            this.httpRequestMethod = method;
            this.url     = URL;
            this.content = content;

            //optional
            this.ContentType = contentType;
            this.Accepts     = acceptsType;
            this.UserAgent   = userAgent;

            isReceived = false;
        }
Esempio n. 53
0
        /// <summary>
        /// 请求服务器
        /// </summary>
        /// <param name="url">url</param>
        /// <param name="requestForm">请求表单信息</param>
        /// <param name="header">请求头</param>
        /// <returns></returns>
        public string Request(string url, RequestForm requestForm, Dictionary <string, string> header)
        {
            RequestMethod requestMethod = requestForm.RequestMethod;
            bool          isGet         = requestMethod == RequestMethod.GET;

            if (isGet)
            {
                return(this.doGet(url, requestForm, header));
            }
            else
            {
                return(this.doPost(url, requestForm, header));
            }
        }
 public PollServiceEventArgs(
     RequestMethod pRequest,
     string pUrl,
     HasEventsMethod pHasEvents, GetEventsMethod pGetEvents, NoEventsMethod pNoEvents,
     UUID pId, int pTimeOutms)
 {
     Request = pRequest;
     Url = pUrl;
     HasEvents = pHasEvents;
     GetEvents = pGetEvents;
     NoEvents = pNoEvents;
     Id = pId;
     TimeOutms = pTimeOutms;
     Type = EventType.LongPoll;
 }
        public bool AddBatchUrl(RequestMethod RequestMethod, string Url)
        {
            if (string.IsNullOrEmpty(Url))
                return false;

            FacebookUrl FBUrlObj = new FacebookUrl(RequestMethod, Url);
            if (_AllUrls.Contains(FBUrlObj) == true)
            {
                return false;
            }

            _AllUrls.Add(FBUrlObj);

            return true;
        }
 private string HttpRequest(string command, RequestMethod method, params WorktileParameter[] pars)
 {
     List<WorktileParameter> normal_params = new List<WorktileParameter>();
     foreach (var par in pars)
     {
         if (command.Contains(par.Name))
         {
             command = command.Replace(":" + par.Name, par.Value.ToString());
         }
         else
         {
             normal_params.Add(par);
         }
     }
     return OAuth.Request(string.Format("{0}{1}", BASE_URL, command), method, normal_params.ToArray());
 }
 public static string RequestMethodToString(RequestMethod method)
 {
     switch(method)
     {
         case RequestMethod.GET:
             return "GET";
         case RequestMethod.PUT:
             return "PUT";
         case RequestMethod.POST:
             return "POST";
         case RequestMethod.DELETE:
             return "DELETE";
         default:
             throw new ProxyException("Invalid request method");
     }
 }
Esempio n. 58
0
        /// <summary>
        /// Sends a requests with parameters to the server
        /// </summary>
        /// <param name="method"></param>
        /// <param name="relativeUri"></param>
        /// <param name="param"></param>
        /// <returns></returns>
        public Dictionary Send(RequestMethod method, string relativeUri, Dictionary param) {
            //Serialise the parameters
            JsonWriter data = null;
            if (method == RequestMethod.POST) {
                if (param != null) {
                    data = JsonWriter.Serialize(param);
                }
            }

            //adds the server url
            string uri = _server_uri;
            if (relativeUri != null)
                uri += relativeUri;

            return SendRequest(method, uri, data);
        }
Esempio n. 59
0
        private HttpJsonRequest(Uri url, RequestMethod method, JObject metadata, ICredentials credentials)
        {
            webRequest = WebRequest.Create(url) as HttpWebRequest;
            webRequest.Credentials = credentials;
            WriteMetadata(metadata);
            webRequest.Method = method.GetName();

            switch (method)
            {
                case RequestMethod.POST:
                    webRequest.ContentType = "application/json; charset=utf-8";
                    break;
                default:
                    break;
            }
        }
Esempio n. 60
0
        /// <summary>
        /// Performs an api call on the specified URL 
        /// </summary>
        /// <param name="apiUrl"></param>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public ExtApiCallResult ExecuteApiCall(string apiUrl, IList<ApiParameter> parameters, RequestMethod method, string username = "", string password = "")
        {
            var client = new RestClient(apiUrl);
            var request = new RestRequest();
            request.Method = ConvertRequestMethod(method);

            // Add all the parameters to the request
            foreach (var param in parameters)
                request.Parameters.Add(new Parameter { Name = param.Name, Value = param.UnencodedValue, Type = ParameterType.GetOrPost });

            // Setup authentication
            if (!string.IsNullOrWhiteSpace(username))
                client.Authenticator = new HttpBasicAuthenticator(username, password);

            // Execute the request
            return CreateExtApiCallResult(client.Execute(request));
        }