Пример #1
0
        private void ProcessRequest(Request request, NetworkStream stream)
        {
            if (request == null)
            {
                return;
            }
            if (request.Path.Equals("/"))
                request.Path = floderPath+"/index.html";
            ParsePath(request);
            if (File.Exists(floderPath+request.Path))
            {
                if(Path.GetExtension(request.Path).ToUpper()==".HTML")
                { 
                    var fileContent = File.ReadAllText(floderPath + request.Path);
                    GenerateResponse(fileContent, stream, OK200);
                    return;
                }
                else
                {
                    
                    byte[] byteContents = File.ReadAllBytes(floderPath + request.Path.Replace(@"/",@"\"));
                    GenerateResponse(byteContents, stream, OK200);
                    return;
                }
            }

            GenerateResponse("Not found", stream, NOTFOUND404);
        }
Пример #2
0
        public static String QueryStringForTR(Request trParams, Request req, String postURL, BraintreeService service)
        {
            String trData = TrUtil.BuildTrData(trParams, "http://example.com", service);
            String postData = "tr_data=" + HttpUtility.UrlEncode(trData, Encoding.UTF8) + "&";
            postData += req.ToQueryString();

            var request = WebRequest.Create(postURL) as HttpWebRequest;

            request.Method = "POST";
            request.KeepAlive = false;

            byte[] buffer = Encoding.UTF8.GetBytes(postData);
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = buffer.Length;
            Stream requestStream = request.GetRequestStream();
            requestStream.Write(buffer, 0, buffer.Length);
            requestStream.Close();

            var response = request.GetResponse() as HttpWebResponse;
            String query = response.ResponseUri.Query;

            response.Close();

            return query;
        }
Пример #3
0
        public Response.CsResponse Process(Request.CsRequest request)
        {
            string[] lines = File.ReadAllLines("serverlist.txt");
            CsResponse response = new CsResponse();

            foreach (var l in lines)
            {
                if (l.Trim().Length == 0 || l.Trim()[0] == '#')
                    continue;

                var ipPort = l.Trim().Split(new char[] { ':' });

                IPAddress ip;
                short port;
                if (ipPort.Length < 2 || !IPAddress.TryParse(ipPort[0], out ip) || !short.TryParse(ipPort[1], out port))
                    continue;

                response.Servers.Add(new CsResponseItem()
                {
                    IPAddress = ip,
                    Port = port
                });
            }

            return response;
        }
Пример #4
0
        /// <summary>
        /// Retrieve the UUID given a username
        /// This one is no longer used during auth since the new method get the UUID
        /// </summary>
        public static Guid GetUUID(string username)
        {
            using (WebClient client = new WebClient())
            {
                /*
            'header'  => "Content-type: application/json\r\n",
            'method'  => 'POST',
            'content' => '{"name":"'.$username.'","agent":"minecraft"}',

                context  = stream_context_create(options);
                result = file_get_contents(url, false, $context);
                return res;
                */

                var request = new Request();
                request.name = username;

                byte[] req = Json.Serialize(request);

                // Download data.
                byte[] resp = client.UploadData(url, req);
                var response = Json.Deserialize<Response>(resp);

                if(response.profiles.Count == 0)
                    throw new InvalidOperationException("Bad response: " + Encoding.UTF8.GetString(resp));
                Guid id = response.profiles[0].id;
                if (id == Guid.Empty)
                    throw new InvalidOperationException("Bad response: " + Encoding.UTF8.GetString(resp));
                return id;
            }
        }
Пример #5
0
        private static void JSONRequest(Request reqst)
        {
            DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Request));
            MemoryStream mem = new MemoryStream();
            ser.WriteObject(mem, reqst);
            string jsonData = Encoding.UTF8.GetString(mem.ToArray(), 0, (int)mem.Length);
            byte[] byteArray = Encoding.UTF8.GetBytes(jsonData);
            mem.Close();
            mem.Dispose();

            Console.WriteLine(jsonData);

            string json = HTTPRequestResponse(string.Format("{0}/{1}/{2}", _URL, _userID, "json"), byteArray, "PUT", "application/json;charset=\"utf-8\"");
            Console.WriteLine(json);

            DataContractJsonSerializer respSer = new DataContractJsonSerializer(typeof(Response));
            Response resp = (Response)respSer.ReadObject(new MemoryStream(Encoding.Unicode.GetBytes(json)));

            if (resp.IsSuccessful)
            {
                string responseData = _aes.Decrypt(resp.Data, _key);
                Console.WriteLine(responseData);
            }
            else
                Console.WriteLine(resp.ErrorMessage);
        }
Пример #6
0
 public RequestWriter(IRequest rawRequest)
     : this()
 {
     Method = rawRequest.Method;
         Uri = rawRequest.Uri;
         TheRealBodyBytes = new Request(rawRequest).BodyBytes;
 }
Пример #7
0
        public PageResult Analyze(Request request, Response response)
        {
            Console.WriteLine(@"FakePageAnalyzer.Analyze 执行分析");

            request = new Request()
            {
                SiteId = SiteIndex.Usashopcn,
                Url = @"http://www.usashopcn.com/Product/Details/127824",
                HttpMethod = HttpMethod.Get,
                RemainRetryCount = 0
            };

            response = new Response()
            {
                Request = request,
                HttpStatusCode = HttpStatusCode.OK,
                ReasonPhrase = "OK",
                IsSuccessCode = true,
                Content = "测试文本",
                MillisecondTime = 1000,
                Downloader = "FakeDownloader"
            };

            return new PageResult()
            {
                Topic = TopicType.StaticHtml,
                Request = request,
                Response = response
            };
        }
Пример #8
0
        /// <summary>
        /// GetStream
        /// </summary>
        /// <param name="request">request</param>
        /// <returns>Stream</returns>
        internal static Stream GetStream(Request request)
        {
            HttpWebResponse response = null;
            Stream responseStream = null;
            try
            {
                var httpWebRequest = GetHttpWebRequest(request);
                response = (HttpWebResponse)httpWebRequest.GetResponse();
                responseStream = response.GetResponseStream();
                byte[] buffer = StreamToBytes(responseStream);
                Stream memoryStream = new MemoryStream(buffer);
                request.Cookie = httpWebRequest.CookieContainer;
                return memoryStream;
            }
            catch (Exception)
            {
                return null;
            }
            finally
            {
                if (responseStream != null)
                {
                    responseStream.Dispose();
                    responseStream.Close();
                }

                if (response != null)
                {
                    response.Dispose();
                    response.Close();
                }
            }
        }
        public RequestReceivedEventArgs(Request request, Socket client, int byteCount)
        {
            this.request = request;
            this.client = client;
            this.byteCount = byteCount;

            this.receiveTime = DateTime.Now;
        }
Пример #10
0
            public override Task<Response> ProcessRequest(Request request)
            {
                if (this.RequestReceived != null)
                {
                    return Task.FromResult(this.RequestReceived(request));
                }

                return Task.FromResult(request.CreateErrorResponse(HttpStatusCode.Gone, "Gone fishin'."));
            }
Пример #11
0
        public static AppAction App()
        {
            return (env, fault, result) => {
                var request = new Request(env);
                var response = new Response(result);
                if (string.IsNullOrWhiteSpace(request.GET["Url"])) {
                    response.ContentType = "text/html";
                    response
                        .Write("<form>")
                        .Write("Url <input type='text' name='Url' style='width:50%;' value='http://download.microsoft.com/download/f/e/6/fe6eb291-e187-4b06-ad78-bb45d066c30f/6.0.6001.18000.367-KRMSDK_EN.iso'/><br/>")
                        .Write("Save as <input type='text' name='SaveAs' style='width:50%;' value='6.0.6001.18000.367-KRMSDK_EN.iso'/><br/>")
                        .Write("<input type='submit' value='Go'/>")
                        .Write("</form>")
                        .Finish();
                }
                else {
                    // make remote request asynchronously
                    var remoteRequest = WebRequest.Create(request.GET["Url"]);

                    remoteRequest.BeginGetResponse(getResponseResult => fault.Guard(() => {
                        var remoteResponse = (HttpWebResponse)remoteRequest.EndGetResponse(getResponseResult);

                        // pass some response headers along
                        response.Status = (int)remoteResponse.StatusCode;
                        response.ContentType = remoteResponse.ContentType;
                        if (!string.IsNullOrWhiteSpace(request.GET["SaveAs"])) {
                            response.AddHeader("Content-Disposition", "attachment; filename=" + request.GET["SaveAs"]);
                        }

                        // pass response body along
                        var remoteStream = remoteResponse.GetResponseStream();
                        if (remoteStream == null) {
                            response.Finish();
                        }
                        else {
                            var buffer = new byte[4096];
                            response.Finish((next, error, complete) =>
                                Loop.Run((halted, continuation) => error.Guard(() =>
                                    remoteStream.BeginRead(buffer, 0, buffer.Length, streamResult => error.Guard(() => {
                                        var count = remoteStream.EndRead(streamResult);
                                        if (halted()) {
                                            return;
                                        }
                                        if (count <= 0) {
                                            complete();
                                            return;
                                        }
                                        if (!next.InvokeAsync(new ArraySegment<byte>(buffer, 0, count), continuation)) {
                                            continuation();
                                        }
                                    }), null))));
                        }
                    }), null);
                }
            };
        }
Пример #12
0
        public override Task<Response> ProcessRequest(Request request)
        {
            // The '.Servers' property actually returns a new list so this is totally reasonable.
            var response = new ListServerResponse {Servers = this.serverList.Servers};
            if (response.Servers.Count == 0)
            {
                return Task.FromResult(request.CreateErrorResponse(HttpStatusCode.NotFound, "No known servers."));
            }

            return Task.FromResult(Response.Create(request, HttpStatusCode.OK, response));
        }
Пример #13
0
        /// <summary>
        ///     Returns a collection of strings to the client advertizing features this provider supports.
        /// </summary>
        /// <param name="request">
        ///     An object passed in from the CORE that contains functions that can be used to interact with
        ///     the CORE and HOST
        /// </param>
        public void GetFeatures(Request request) {
            if (request == null) {
                throw new ArgumentNullException("request");
            }

            // Nice-to-have put a debug message in that tells what's going on.
            request.Debug("Calling '{0}::GetFeatures' ", ProviderName);
            foreach (var feature in _features) {
                request.Yield(feature);
            }
        }
Пример #14
0
        public void DoSendResponse(Request request, Response response)
        {
            // the http stack is intended to send back only coap responses

            // fill the exchanger with the incoming response
            WaitFuture<Request, Response> wf;
            if (_exchangeMap.TryRemove(request, out wf))
            {
                wf.Response = response;
            }
        }
Пример #15
0
 internal UInt32 AddStream(Request request, Type type)
 {
     var id = this.connection.KRPC ().AddStream (request);
     lock (accessLock) {
         if (!streamTypes.ContainsKey (id)) {
             streamTypes [id] = type;
             streamData [id] = this.connection.Invoke (request);
         }
     }
     return id;
 }
Пример #16
0
        public OAuthAccess(string consumerKey, string consumerSecret, string requestTokenURL, string accessTokenURL, string authorizeURL)
        {
            this.req = new Request();
            this.rnd = new Random();

            this.consumerKey = consumerKey;
            this.consumerSecret = consumerSecret;
            this.requestTokenURL = requestTokenURL;
            this.accessTokenURL = accessTokenURL;
            this.authorizeURL = authorizeURL;
        }
Пример #17
0
        public void Should_invoke_route_returned()
        {
            // Given
            var request = new Request("GET", "/", "http");

            // When
            this.engine.HandleRequest(request);

            // Then
            A.CallTo(() => this.route.Invoke()).MustHaveHappened();
        }
Пример #18
0
 public Dictionary<string, string> GetHeaders(Request request)
 {
     switch (Method)
     {
         case SignatureMethod.PLAINTEXT:
             return GeneratePlainOAuthHeaders(request);
         case SignatureMethod.HMACSHA1:
             return GenerateHmacOAuthHeaders(request);
         default:
             return null;
     }
 }
Пример #19
0
 public ClosureCodeRequest(string apiUrl, CompilationLevel level, string jsContent)
 {
     apiUrl = string.IsNullOrEmpty(apiUrl) ? DefaultApiUrl : apiUrl;
     request = new Request(apiUrl,
         new List<KeyValuePair<string, string>>
             {
                      new KeyValuePair<string, string>("compilation_level", level.ToString()),
                      new KeyValuePair<string, string>("js_code", jsContent),
                      new KeyValuePair<string, string>("output_format", "xml"),
                      new KeyValuePair<string, string>("output_info", "compiled_code"),
                 });
 }
Пример #20
0
 public UInt32 AddStream (Request request, Type type)
 {
     CheckDisposed ();
     var id = connection.KRPC ().AddStream (request);
     lock (accessLock) {
         if (!streamTypes.ContainsKey (id)) {
             streamTypes [id] = type;
             streamData [id] = connection.Invoke (request);
         }
     }
     return id;
 }
Пример #21
0
        protected override Response ForwardRequest(Request incomingCoapRequest)
        {
            // check the invariant: the request must have the proxy-uri set
            if (!incomingCoapRequest.HasOption(OptionType.ProxyUri))
            {
                if (log.IsWarnEnabled)
                    log.Warn("Proxy-uri option not set.");
                return new Response(StatusCode.BadOption);
            }

            // remove the fake uri-path
            incomingCoapRequest.RemoveOptions(OptionType.UriPath); // HACK

            // get the proxy-uri set in the incoming coap request
            Uri proxyUri;
            try
            {
                proxyUri = incomingCoapRequest.ProxyUri;
            }
            catch (UriFormatException e)
            {
                if (log.IsWarnEnabled)
                    log.Warn("Proxy-uri option malformed: " + e.Message);
                return new Response(StatusCode.BadOption);
            }

            WebRequest httpRequest = null;
            try
            {
                httpRequest = HttpTranslator.GetHttpRequest(incomingCoapRequest);
            }
            catch (TranslationException e)
            {
                if (log.IsWarnEnabled)
                    log.Warn("Problems during the http/coap translation: " + e.Message);
                return new Response(StatusCode.BadGateway);
            }

            HttpWebResponse httpResponse = (HttpWebResponse)httpRequest.GetResponse();
            DateTime timestamp = DateTime.Now;
            try
            {
                Response coapResponse = HttpTranslator.GetCoapResponse(httpResponse, incomingCoapRequest);
                coapResponse.Timestamp = timestamp;
                return coapResponse;
            }
            catch (TranslationException e)
            {
                if (log.IsWarnEnabled)
                    log.Warn("Problems during the http/coap translation: " + e.Message);
                return new Response(StatusCode.BadGateway);
            }
        }
Пример #22
0
 private async void albumGenreView_SelectionChanged(object sender, SelectionChangedEventArgs e)
 {
     LongListSelector lls = sender as LongListSelector;
     if (lls.SelectedItem == null)
         return;
     ItemViewModel item = lls.SelectedItem as ItemViewModel;
     var rq = new Request(Request.Count);
     await App.AlbumListView.LoadDataInit(item.LineTwo);
     await App.SongsView.LoadInit(item.LineThree);
     if (rq.Id == Request.Count - 1)
         albumViewPivot.SelectedIndex = 1;
     lls.SelectedItem = null;
 }
Пример #23
0
        public void Should_call_route_resolver_with_all_route_handlers()
        {
            // Given
            var request = new Request("PUT", "/");

            A.CallTo(() => this.application.ModuleMetas).Returns(this.modules);

            // When
            this.engine.HandleRequest(request);

            // Then
            A.CallTo(() => this.resolver.GetRoute(A<Request>.Ignored.Argument, A<IEnumerable<ModuleMeta>>.That.Matches(x => x.SequenceEqual(this.modules["PUT"])).Argument, A<INancyApplication>.Ignored.Argument)).MustHaveHappened();
        }
 public void GetResponse(Action<IResponse, Action> responseCallback) {
     if(_received < _dataLength) {
         var badRequest = new Request(_client, _command, _arguments, 0, new List<byte[]>());
         _errorHandler(badRequest, new DataExpectationException(_dataLength, _received), response => responseCallback(response, null));
         return; 
     }
     var request = new Request(_client, _command, _arguments, _dataLength, _dataChunks);
     try {
         _handler(request, responseCallback);
     } catch(Exception e) {
         _errorHandler(request, e, response => responseCallback(response, null));
     }
 }
 public IEnumerable<IResponse> GetResponse() {
     if(_received < _dataLength) {
         var badRequest = new Request(_client, _command, _arguments, 0, new List<byte[]>());
         return new[] {_errorHandler(badRequest, new DataExpectationException(_dataLength, _received))};
     }
     var request = new Request(_client, _command, _arguments, _dataLength, _dataChunks);
     IResponse response;
     try {
         response = _handler(request);
     } catch(Exception e) {
         response = _errorHandler(request, e);
     }
     return new[] { response };
 }
Пример #26
0
        public void Should_call_route_resolver_with_request()
        {
            // Given
            var request = new Request("GET", "/");

            A.CallTo(() => this.application.ModuleMetas).Returns(this.modules);

            // When
            this.engine.HandleRequest(request);

            // Then
            A.CallTo(() => this.resolver.GetRoute(request,
                A<IEnumerable<ModuleMeta>>.Ignored.Argument, A<INancyApplication>.Ignored.Argument)).MustHaveHappened();
        }
Пример #27
0
        public void Should_call_route_resolver_with_request()
        {
            // Given
            var request = new Request("GET", "/", new Dictionary<string, IEnumerable<string>>(), new MemoryStream());

            A.CallTo(() => this.locator.GetModules()).Returns(this.modules);

            // When
            this.engine.HandleRequest(request);

            // Then
            A.CallTo(() => this.resolver.GetRoute(request,
                A<IEnumerable<RouteDescription>>.Ignored.Argument)).MustHaveHappened();
        }
Пример #28
0
        public void Should_ignore_case_of_request_verb_when_resolving_route_handlers(string verb)
        {
            // Given
            var request = new Request(verb, "/");

            A.CallTo(() => this.application.ModuleMetas).Returns(this.modules);

            // When
            this.engine.HandleRequest(request);

            // Then
            A.CallTo(() => this.resolver.GetRoute(A<Request>.Ignored.Argument,
                A<IEnumerable<ModuleMeta>>.Ignored.Argument, A<INancyApplication>.Ignored.Argument)).MustHaveHappened();
        }
Пример #29
0
        public void Should_call_route_resolver_with_all_route_handlers()
        {
            // Given
            var request = new Request("PUT", "/", new Dictionary<string, IEnumerable<string>>(), new MemoryStream());
            var descriptions = GetRouteDescriptions(request, this.modules);

            A.CallTo(() => this.locator.GetModules()).Returns(this.modules);
            A.CallTo(() => this.resolver.GetRoute(request, descriptions)).Returns(null);

            // When
            this.engine.HandleRequest(request);

            // Then
            A.CallTo(() => this.resolver.GetRoute(A<Request>.Ignored.Argument, A<IEnumerable<RouteDescription>>.That.Matches(x => x.SequenceEqual(descriptions)).Argument)).MustHaveHappened();
        }
Пример #30
-1
        public JettyWebConnection(IWebServer webServer, String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response)
            : base(webServer, CallingFrom.Web)
        {
            Response = response;
            BaseRequest = baseRequest;
            Request = request;

            _RequestedFile = target;

            org.eclipse.jetty.io.EndPoint jettyEndpoint = baseRequest.getConnection().getEndPoint();
            string remoteAddress = jettyEndpoint.getRemoteAddr();
            int remotePort = jettyEndpoint.getRemotePort();

            _RemoteEndPoint = new IPEndPoint(IPAddress.Parse(remoteAddress), remotePort);
        }