/// <summary>
        /// Executes a request using the default context and processes the
        /// response using the given response handler.
        /// </summary>
        /// <remarks>
        /// Executes a request using the default context and processes the
        /// response using the given response handler. The content entity associated
        /// with the response is fully consumed and the underlying connection is
        /// released back to the connection manager automatically in all cases
        /// relieving individual
        /// <see cref="Apache.Http.Client.ResponseHandler{T}">Apache.Http.Client.ResponseHandler&lt;T&gt;
        ///     </see>
        /// s from having to manage
        /// resource deallocation internally.
        /// </remarks>
        /// <param name="request">the request to execute</param>
        /// <param name="responseHandler">the response handler</param>
        /// <param name="context">
        /// the context to use for the execution, or
        /// <code>null</code> to use the default context
        /// </param>
        /// <returns>the response object as generated by the response handler.</returns>
        /// <exception cref="System.IO.IOException">in case of a problem or the connection was aborted
        ///     </exception>
        /// <exception cref="Apache.Http.Client.ClientProtocolException">in case of an http protocol error
        ///     </exception>
        public virtual T Execute <T, _T1>(IHttpUriRequest request, ResponseHandler <_T1> responseHandler
                                          , HttpContext context) where _T1 : T
        {
            HttpHost target = DetermineTarget(request);

            return(Execute(target, request, responseHandler, context));
        }
        internal async Task <bool> RunInternal(Dictionary <Type, object> viewModelsMapping, IPreviewer previewer)
        {
            if (isRunning)
            {
                return(true);
            }
            mainScheduler = TaskScheduler.FromCurrentSynchronizationContext();
            host          = await HttpHost.StartServer(this, Constants.DEFAULT_PORT, PORTS_RANGE);

            if (host == null)
            {
                Log.Error("Couldn't start server");
                return(false);
            }
            broadcaster = new DiscoveryBroadcaster(port, true);
            await broadcaster.Start();

            if (viewModelsMapping == null)
            {
                viewModelsMapping = new Dictionary <Type, object>();
            }
            if (previewer == null)
            {
                previewer = new Previewer(viewModelsMapping);
            }
            this.previewer = previewer;
            vm             = new VM();
            isRunning      = true;
            return(true);
        }
        /// <summary>
        /// Derives the interpreted (absolute) URI that was used to generate the last
        /// request.
        /// </summary>
        /// <remarks>
        /// Derives the interpreted (absolute) URI that was used to generate the last
        /// request. This is done by extracting the request-uri and target origin for
        /// the last request and scanning all the redirect locations for the last
        /// fragment identifier, then combining the result into a
        /// <see cref="Sharpen.URI">Sharpen.URI</see>
        /// .
        /// </remarks>
        /// <param name="originalURI">original request before any redirects</param>
        /// <param name="target">
        /// if the last URI is relative, it is resolved against this target,
        /// or <code>null</code> if not available.
        /// </param>
        /// <param name="redirects">
        /// collection of redirect locations since the original request
        /// or <code>null</code> if not available.
        /// </param>
        /// <returns>interpreted (absolute) URI</returns>
        /// <exception cref="Sharpen.URISyntaxException"></exception>
        public static URI Resolve(URI originalURI, HttpHost target, IList <URI> redirects)
        {
            Args.NotNull(originalURI, "Request URI");
            URIBuilder uribuilder;

            if (redirects == null || redirects.IsEmpty())
            {
                uribuilder = new URIBuilder(originalURI);
            }
            else
            {
                uribuilder = new URIBuilder(redirects[redirects.Count - 1]);
                string frag = uribuilder.GetFragment();
                // read interpreted fragment identifier from redirect locations
                for (int i = redirects.Count - 1; frag == null && i >= 0; i--)
                {
                    frag = redirects[i].GetFragment();
                }
                uribuilder.SetFragment(frag);
            }
            // read interpreted fragment identifier from original request
            if (uribuilder.GetFragment() == null)
            {
                uribuilder.SetFragment(originalURI.GetFragment());
            }
            // last target origin
            if (target != null && !uribuilder.IsAbsolute())
            {
                uribuilder.SetScheme(target.GetSchemeName());
                uribuilder.SetHost(target.GetHostName());
                uribuilder.SetPort(target.GetPort());
            }
            return(uribuilder.Build());
        }
        public virtual void AuthSucceeded(HttpHost authhost, AuthScheme authScheme, HttpContext
                                          context)
        {
            Args.NotNull(authhost, "Host");
            Args.NotNull(authScheme, "Auth scheme");
            Args.NotNull(context, "HTTP context");
            HttpClientContext clientContext = ((HttpClientContext)HttpClientContext.Adapt(context
                                                                                          ));

            if (IsCachable(authScheme))
            {
                AuthCache authCache = clientContext.GetAuthCache();
                if (authCache == null)
                {
                    authCache = new BasicAuthCache();
                    clientContext.SetAuthCache(authCache);
                }
                if (this.log.IsDebugEnabled())
                {
                    this.log.Debug("Caching '" + authScheme.GetSchemeName() + "' auth scheme for " +
                                   authhost);
                }
                authCache.Put(authhost, authScheme);
            }
        }
Exemple #5
0
        /// <exception cref="Apache.Http.Conn.UnsupportedSchemeException"></exception>
        public virtual int Resolve(HttpHost host)
        {
            Args.NotNull(host, "HTTP host");
            int port = host.GetPort();

            if (port > 0)
            {
                return(port);
            }
            else
            {
                string name = host.GetSchemeName();
                if (Sharpen.Runtime.EqualsIgnoreCase(name, "http"))
                {
                    return(80);
                }
                else
                {
                    if (Sharpen.Runtime.EqualsIgnoreCase(name, "https"))
                    {
                        return(443);
                    }
                    else
                    {
                        throw new UnsupportedSchemeException(name + " protocol is not supported");
                    }
                }
            }
        }
        /// <exception cref="Apache.Http.HttpException"></exception>
        protected internal override HttpHost DetermineProxy(HttpHost target, IHttpRequest
                                                            request, HttpContext context)
        {
            URI targetURI;

            try
            {
                targetURI = new URI(target.ToURI());
            }
            catch (URISyntaxException ex)
            {
                throw new HttpException("Cannot convert host to URI: " + target, ex);
            }
            IList <Proxy> proxies = this.proxySelector.Select(targetURI);
            Proxy         p       = ChooseProxy(proxies);
            HttpHost      result  = null;

            if (p.Type() == Proxy.Type.Http)
            {
                // convert the socket address to an HttpHost
                if (!(p.Address() is IPEndPoint))
                {
                    throw new HttpException("Unable to handle non-Inet proxy address: " + p.Address()
                                            );
                }
                IPEndPoint isa = (IPEndPoint)p.Address();
                // assume default scheme (http)
                result = new HttpHost(GetHost(isa), isa.Port);
            }
            return(result);
        }
        /// <summary>
        /// A convenience method for creating a new
        /// <see cref="Sharpen.URI">Sharpen.URI</see>
        /// whose scheme, host
        /// and port are taken from the target host, but whose path, query and
        /// fragment are taken from the existing URI. The fragment is only used if
        /// dropFragment is false. The path is set to "/" if not explicitly specified.
        /// </summary>
        /// <param name="uri">Contains the path, query and fragment to use.</param>
        /// <param name="target">Contains the scheme, host and port to use.</param>
        /// <param name="dropFragment">True if the fragment should not be copied.</param>
        /// <exception cref="Sharpen.URISyntaxException">If the resulting URI is invalid.</exception>
        public static URI RewriteURI(URI uri, HttpHost target, bool dropFragment)
        {
            Args.NotNull(uri, "URI");
            if (uri.IsOpaque())
            {
                return(uri);
            }
            URIBuilder uribuilder = new URIBuilder(uri);

            if (target != null)
            {
                uribuilder.SetScheme(target.GetSchemeName());
                uribuilder.SetHost(target.GetHostName());
                uribuilder.SetPort(target.GetPort());
            }
            else
            {
                uribuilder.SetScheme(null);
                uribuilder.SetHost(null);
                uribuilder.SetPort(-1);
            }
            if (dropFragment)
            {
                uribuilder.SetFragment(null);
            }
            if (TextUtils.IsEmpty(uribuilder.GetPath()))
            {
                uribuilder.SetPath("/");
            }
            return(uribuilder.Build());
        }
Exemple #8
0
        }                                             // Ссылка для сервиса

        static void Main(string[] args)
        {
            try
            {
                // Service configure
                ServiceUrl = @"http://*****:*****@"C:\tmp\ks\"; // путь к служебным файлам (БД, логи)
                System.IO.Directory.CreateDirectory(_workPath);
                DbPath = _workPath + @"clientDB.db";
                string log_path = _workPath + @"Writter_.log";

                // Инициализация сервиса
                InitDB(DbPath);
                InitLogger(log_path);
                InitSoapService();

                // Ожидание команды на закрытие сервиса
                Console.ReadLine();
                // Закрываем службу

                HttpHost.Close();
                CloseDB(DbPath);
                Log.Information("Service stopped");
            }
            catch (Exception e)
            {
                Log.Fatal(e.Message);
                Console.WriteLine(e);
                Console.ReadLine();
            }
        }
Exemple #9
0
        /// <exception cref="System.IO.IOException"></exception>
        public virtual void Upgrade(ManagedHttpClientConnection conn, HttpHost host, HttpContext
                                    context)
        {
            HttpClientContext clientContext = ((HttpClientContext)HttpClientContext.Adapt(context
                                                                                          ));
            Lookup <ConnectionSocketFactory> registry = GetSocketFactoryRegistry(clientContext
                                                                                 );
            ConnectionSocketFactory sf = registry.Lookup(host.GetSchemeName());

            if (sf == null)
            {
                throw new UnsupportedSchemeException(host.GetSchemeName() + " protocol is not supported"
                                                     );
            }
            if (!(sf is LayeredConnectionSocketFactory))
            {
                throw new UnsupportedSchemeException(host.GetSchemeName() + " protocol does not support connection upgrade"
                                                     );
            }
            LayeredConnectionSocketFactory lsf = (LayeredConnectionSocketFactory)sf;

            System.Net.Sockets.Socket sock = conn.GetSocket();
            int port = this.schemePortResolver.Resolve(host);

            sock = lsf.CreateLayeredSocket(sock, host.GetHostName(), port, context);
            conn.Bind(sock);
        }
Exemple #10
0
        private void DoPreemptiveAuth(HttpHost host, AuthScheme authScheme, AuthState authState
                                      , CredentialsProvider credsProvider)
        {
            string schemeName = authScheme.GetSchemeName();

            if (this.log.IsDebugEnabled())
            {
                this.log.Debug("Re-using cached '" + schemeName + "' auth scheme for " + host);
            }
            AuthScope   authScope = new AuthScope(host, AuthScope.AnyRealm, schemeName);
            Credentials creds     = credsProvider.GetCredentials(authScope);

            if (creds != null)
            {
                if (Sharpen.Runtime.EqualsIgnoreCase("BASIC", authScheme.GetSchemeName()))
                {
                    authState.SetState(AuthProtocolState.Challenged);
                }
                else
                {
                    authState.SetState(AuthProtocolState.Success);
                }
                authState.Update(authScheme, creds);
            }
            else
            {
                this.log.Debug("No credentials for preemptive authentication");
            }
        }
 /// <exception cref="System.IO.IOException"></exception>
 public virtual System.Net.Sockets.Socket ConnectSocket(int connectTimeout, System.Net.Sockets.Socket
                                                        socket, HttpHost host, IPEndPoint remoteAddress, IPEndPoint localAddress, HttpContext
                                                        context)
 {
     System.Net.Sockets.Socket sock = socket != null ? socket : CreateSocket(context);
     if (localAddress != null)
     {
         sock.Bind2(localAddress);
     }
     try
     {
         sock.Connect(remoteAddress, connectTimeout);
     }
     catch (IOException ex)
     {
         try
         {
             sock.Close();
         }
         catch (IOException)
         {
         }
         throw;
     }
     return(sock);
 }
Exemple #12
0
        public async Task TestEmptyGetRequest()
        {
            using (var server = new HttpHost(TestPort))
            {
                const string path = "/test/path?query=value";

                await server.OpenAsync(request =>
                {
                    Assert.Equal(path, request.RequestUri.PathAndQuery);

                    Assert.Equal(HttpMethod.Get, request.Method);

                    return(Task.FromResult(new HttpResponseMessage {
                        StatusCode = HttpStatusCode.Found
                    }));
                });

                using (var client = new HttpClient())
                {
                    var request  = new HttpRequestMessage(HttpMethod.Get, LocalHost + path);
                    var response = await client.SendAsync(request);

                    Assert.Equal(HttpStatusCode.Found, response.StatusCode);
                }
            }
        }
        public async Task <bool> Start()
        {
            host = await HttpHost.StartServer(this, Constants.DEFAULT_CLIENT_PORT, 1);

            if (host == null)
            {
                MessageService.ShowError($"XAMLator: Failed to start the server. There seems to be another instance of VS4MAC is running!");
                return(false);
            }
            try
            {
                listener = new UdpClient(Constants.DISCOVERY_BROADCAST_RECEIVER_PORT, AddressFamily.InterNetwork);
            }
            catch (Exception ex)
            {
                MessageService.ShowError($"XAMLator: Failed to start the discovery receiver", ex);
                Debug.WriteLine("XAMLator: Failed to listen: " + ex);
                listener = null;
            }
            if (listener != null)
            {
                thread = new Thread(Run);
                thread.Start();
            }
            running = true;
            return(true);
        }
        /// <summary>
        /// Uploads the source stream to BunnyCDN.
        /// </summary>
        /// <param name="source">The stream containing the data to upload.</param>
        /// <param name="directory">The directory in BunnyCDN to upload to.</param>
        /// <param name="fileName">The name of the file to create in BunnyCDN.</param>
        /// <returns>An HTTP URI pointing to the new file in BunnyCDN.</returns>
        private async Task <Uri> UploadMedia(Stream source, string directory, string fileName)
        {
            var url = $"{settings.Value.StorageZone}/{directory}/{fileName}";

            using var sourceStreamContent = new StreamContent(source);
            HttpResponseMessage?uploadResponseOrNull = null;

            try
            {
                uploadResponseOrNull = await httpClient.PutAsync(url, sourceStreamContent);

                uploadResponseOrNull.EnsureSuccessStatusCode();
            }
            catch (HttpRequestException uploadError)
            {
                uploadError.Data.Add("directory", directory);
                uploadError.Data.Add("fileName", fileName);
                uploadError.Data.Add("url", url);
                if (uploadResponseOrNull != null)
                {
                    uploadError.Data.Add("statusCode", uploadResponseOrNull.StatusCode);
                    uploadError.Data.Add("reasonPhrase", uploadResponseOrNull.ReasonPhrase);
                }
                throw;
            }
            finally
            {
                uploadResponseOrNull?.Dispose();
            }

            return(HttpHost.Combine(directory, fileName));
        }
        /// <exception cref="System.IO.IOException"></exception>
        /// <exception cref="Apache.Http.Client.ClientProtocolException"></exception>
        protected internal override CloseableHttpResponse DoExecute(HttpHost target, IHttpRequest
                                                                    request, HttpContext context)
        {
            Args.NotNull(target, "Target host");
            Args.NotNull(request, "HTTP request");
            HttpExecutionAware execAware = null;

            if (request is HttpExecutionAware)
            {
                execAware = (HttpExecutionAware)request;
            }
            try
            {
                HttpRequestWrapper wrapper      = HttpRequestWrapper.Wrap(request);
                HttpClientContext  localcontext = ((HttpClientContext)HttpClientContext.Adapt(context
                                                                                              != null ? context : new BasicHttpContext()));
                HttpRoute     route  = new HttpRoute(target);
                RequestConfig config = null;
                if (request is Configurable)
                {
                    config = ((Configurable)request).GetConfig();
                }
                if (config != null)
                {
                    localcontext.SetRequestConfig(config);
                }
                return(this.requestExecutor.Execute(route, wrapper, localcontext, execAware));
            }
            catch (HttpException httpException)
            {
                throw new ClientProtocolException(httpException);
            }
        }
        public IHttpHostConfiguration CreateHostConfiguration(HttpHost host)
        {
            var hostConfiguration = new HttpHostConfiguration(this, host);

            _hosts.Add(hostConfiguration);

            return(hostConfiguration);
        }
Exemple #17
0
 /// <summary>Tracks connecting to the first proxy.</summary>
 /// <remarks>Tracks connecting to the first proxy.</remarks>
 /// <param name="proxy">the proxy connected to</param>
 /// <param name="secure">
 /// <code>true</code> if the route is secure,
 /// <code>false</code> otherwise
 /// </param>
 public void ConnectProxy(HttpHost proxy, bool secure)
 {
     Args.NotNull(proxy, "Proxy host");
     Asserts.Check(!this.connected, "Already connected");
     this.connected  = true;
     this.proxyChain = new HttpHost[] { proxy };
     this.secure     = secure;
 }
        public virtual bool IsAuthenticationRequested(HttpHost authhost, HttpResponse response
                                                      , HttpContext context)
        {
            Args.NotNull(response, "HTTP response");
            int status = response.GetStatusLine().GetStatusCode();

            return(status == this.challengeCode);
        }
        public IHttpHost Host(HttpHostSettings settings)
        {
            var httpHost = new HttpHost(settings);

            _hosts.Add(httpHost);

            return(httpHost);
        }
Exemple #20
0
 static void Main(string[] args)
 {
     var host = new HttpHost("http://localhost:8080");
     host.Add(new CommandBind(new VerySimpleCommand(), HttpMethod.Get, new UriTemplate("*")));
     host.Open();
     Console.WriteLine("Server is running, press any key to continue...");
     Console.ReadKey();
     host.Close();
 }
 /// <summary>
 /// Creates a HttpHostConnectException based on original
 /// <see cref="System.IO.IOException">System.IO.IOException</see>
 /// .
 /// </summary>
 /// <since>4.3</since>
 public HttpHostConnectException(IOException cause, HttpHost host, params IPAddress
                                 [] remoteAddresses) : base("Connect to " + (host != null ? host.ToHostString() :
                                                                             "remote host") + (remoteAddresses != null && remoteAddresses.Length > 0 ? " " +
                                                                                               Arrays.AsList(remoteAddresses) : string.Empty) + ((cause != null && cause.Message
                                                                                                                                                  != null) ? " failed: " + cause.Message : " refused"))
 {
     this.host = host;
     Sharpen.Extensions.InitCause(this, cause);
 }
 public async Task HttpHost_NoEndpoints()
 {
     var host = new HttpHost(new ConfigurationHostSettings("http", "localhost", 8080, HttpMethod.Post));
     var handle = await host.Start();
     using (var tokenSource = new CancellationTokenSource(TimeSpan.FromMinutes(1)))
     {
         await handle.Stop(tokenSource.Token);
     }
 }
Exemple #23
0
 static void Main(string[] args)
 {
     var host = new HttpHost("http://localhost:8080");
     host.Add(DefaultMethodBasedCommandFactory.GetCommandsFor(typeof(Controller)));
     host.Open();
     Console.WriteLine("Server is running, press any key to continue...");
     Console.ReadKey();
     host.Close();
 }
Exemple #24
0
 /// <summary>Creates a new route tracker.</summary>
 /// <remarks>
 /// Creates a new route tracker.
 /// The target and origin need to be specified at creation time.
 /// </remarks>
 /// <param name="target">the host to which to route</param>
 /// <param name="local">
 /// the local address to route from, or
 /// <code>null</code> for the default
 /// </param>
 public RouteTracker(HttpHost target, IPAddress local)
 {
     // the attributes above are fixed at construction time
     // now follow attributes that indicate the established route
     Args.NotNull(target, "Target host");
     this.targetHost   = target;
     this.localAddress = local;
     this.tunnelled    = RouteInfo.TunnelType.Plain;
     this.layered      = RouteInfo.LayerType.Plain;
 }
Exemple #25
0
        static void Main(string[] args)
        {
            var host = new HttpHost("http://localhost:8080");

            host.Add(new CommandBind(new VerySimpleCommand(), HttpMethod.Get, new UriTemplate("*")));
            host.Open();
            Console.WriteLine("Server is running, press any key to continue...");
            Console.ReadKey();
            host.Close();
        }
Exemple #26
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Before @Override public void setUp() throws Exception
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public override void SetUp()
        {
            base.SetUp();
            Handler = new PingerHandler();
            this.serverBootstrap.registerHandler("/*", Handler);
            HttpHost target = start();

            _hostname  = target.HostName;
            _serverUrl = "http://" + _hostname + ":" + target.Port;
        }
        public IHttpHost Host(HttpHostSettings settings)
        {
            var hostTopology = new HttpHostTopology(_configuration.Topology);

            var httpHost = new HttpHost(settings, hostTopology);

            _hosts.Add(httpHost);

            return(httpHost);
        }
        public HttpHostConfiguration(IHttpBusConfiguration busConfiguration, HttpHostSettings settings, IHostTopology hostTopology)
        {
            _busConfiguration = busConfiguration;
            _settings         = settings;
            _hostTopology     = hostTopology;

            HostAddress = settings.GetInputAddress();

            _host = new HttpHost(this);
        }
Exemple #29
0
        static void Main(string[] args)
        {
            var host = new HttpHost("http://localhost:8080");

            host.Add(DefaultMethodBasedCommandFactory.GetCommandsFor(typeof(ToDoController)));
            host.Open();
            Console.WriteLine("Server is running, press any key to continue...");
            Console.ReadKey();
            host.Close();
        }
Exemple #30
0
        public async Task HttpHost_NoEndpoints()
        {
            var host   = new HttpHost(new ConfigurationHostSettings("http", "localhost", 8080, HttpMethod.Post));
            var handle = await host.Start();

            using (var tokenSource = new CancellationTokenSource(TimeSpan.FromMinutes(1)))
            {
                await handle.Stop(tokenSource.Token);
            }
        }
        public IHttpHost Host(HttpHostSettings settings)
        {
            var hostTopology = new HttpHostTopology(_busEndpointConfiguration.Topology);

            var host = new HttpHost(settings, hostTopology);

            _configuration.CreateHostConfiguration(host);

            return(host);
        }
        protected HttpWebRequest GetHttpWebRequest(Request request, Site site, IDictionary headers)
        {
            if (site == null)
            {
                return(null);
            }

            HttpWebRequest httpWebRequest = SelectRequestMethod(request);

            httpWebRequest.UserAgent = site.UserAgent ??
                                       "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:39.0) Gecko/20100101 Firefox/39.0Mozilla/5.0 (Windows NT 10.0; WOW64; rv:39.0) Gecko/20100101 Firefox/39.0";

            if (site.IsUseGzip)
            {
                httpWebRequest.Headers.Add("Accept-Encoding", "gzip");
            }

            // headers
            if (headers != null)
            {
                var enumerator = headers.GetEnumerator();
                while (enumerator.MoveNext())
                {
                    var key   = enumerator.Key;
                    var value = enumerator.Value;
                    httpWebRequest.Headers.Add(key.ToString(), value.ToString());
                }
            }

            // cookie
            httpWebRequest = GeneratorCookie(httpWebRequest, site);

            //check:
            httpWebRequest.Timeout           = site.Timeout;
            httpWebRequest.ContinueTimeout   = site.Timeout;
            httpWebRequest.ReadWriteTimeout  = site.Timeout;
            httpWebRequest.AllowAutoRedirect = true;

            if (headers != null)
            {
                foreach (DictionaryEntry entry in headers)
                {
                    httpWebRequest.Headers.Add(entry.Key.ToString(), entry.Value.ToString());
                }
            }

            if (site.GetHttpProxyPool().Enable)
            {
                HttpHost host = site.GetHttpProxyFromPool();
                httpWebRequest.Proxy = new WebProxy(host.Host, host.Port);
                request.PutExtra(Request.Proxy, host);
            }

            return(httpWebRequest);
        }
Exemple #33
0
        public async Task TestPostRequestWithCustomeHeadersAndBody()
        {
            using (var server = new HttpHost(TestPort))
            {
                const string path    = "/test/path?query=value";
                var          headers = new Dictionary <string, string>
                {
                    { "custom-header-1", "custom-value-1" }, { "content-custom", "content-value" }
                };
                const string contentType     = "suave/test";
                const string content         = "string content";
                var          responseContent = new byte[] { 1, 2, 3 };

                await server.OpenAsync(async request =>
                {
                    Assert.Equal(path, request.RequestUri.PathAndQuery);

                    Assert.Equal(HttpMethod.Post, request.Method);

                    Assert.True(headers.All(pair => request.Headers.First(s => s.Key == pair.Key).Value.First() == pair.Value));

                    Assert.Equal(contentType, request.Content.Headers.ContentType.ToString());

                    Assert.Equal(content, await request.Content.ReadAsStringAsync());

                    var response = new HttpResponseMessage
                    {
                        StatusCode = HttpStatusCode.Accepted,
                        Content    = new ByteArrayContent(responseContent)
                    };
                    response.Headers.Add("server-custom", "server-value");
                    return(response);
                });

                using (var client = new HttpClient())
                {
                    var request = new HttpRequestMessage(HttpMethod.Post, LocalHost + path);
                    headers.Aggregate(request.Headers, (a, b) =>
                    {
                        a.Add(b.Key, b.Value);
                        return(a);
                    });
                    request.Content = new StringContent(content);
                    request.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType);

                    var response = await client.SendAsync(request);

                    Assert.Equal(HttpStatusCode.Accepted, response.StatusCode);

                    Assert.Equal(responseContent, await response.Content.ReadAsByteArrayAsync());

                    Assert.Equal("server-value", response.Headers.First(s => s.Key == "server-custom").Value.First());
                }
            }
        }
        public async Task TestPostRequestWithCustomeHeadersAndBody()
        {
            using (var server = new HttpHost(TestPort))
            {
                const string path = "/test/path?query=value";
                var headers = new Dictionary<string, string>
                    { { "custom-header-1", "custom-value-1" }, { "content-custom", "content-value" } };
                const string contentType = "suave/test";
                const string content = "string content";
                var responseContent = new byte[] { 1, 2, 3 };

                await server.OpenAsync(async request =>
                {
                    Assert.Equal(path, request.RequestUri.PathAndQuery);

                    Assert.Equal(HttpMethod.Post, request.Method);

                    Assert.True(headers.All(pair => request.Headers.First(s => s.Key == pair.Key).Value.First() == pair.Value));

                    Assert.Equal(contentType, request.Content.Headers.ContentType.ToString());

                    Assert.Equal(content, await request.Content.ReadAsStringAsync());

                    var response =  new HttpResponseMessage
                    {
                        StatusCode = HttpStatusCode.Accepted,
                        Content = new ByteArrayContent(responseContent)
                    };
                    response.Headers.Add("server-custom", "server-value");
                    return response;
                });

                using (var client = new HttpClient())
                {
                    var request = new HttpRequestMessage(HttpMethod.Post, LocalHost + path);
                    headers.Aggregate(request.Headers, (a, b) =>
                    {
                        a.Add(b.Key, b.Value);
                        return a;
                    });
                    request.Content = new StringContent(content);
                    request.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType);

                    var response = await client.SendAsync(request);
                    
                    Assert.Equal(HttpStatusCode.Accepted, response.StatusCode);

                    Assert.Equal(responseContent, await response.Content.ReadAsByteArrayAsync());

                    Assert.Equal("server-value", response.Headers.First(s => s.Key == "server-custom").Value.First());
                }
            }
        }
        public async Task TestEmptyGetRequest()
        {
            using (var server = new HttpHost(TestPort))
            {
                const string path = "/test/path?query=value";

                await server.OpenAsync(request =>
                {
                    Assert.Equal(path, request.RequestUri.PathAndQuery);

                    Assert.Equal(HttpMethod.Get, request.Method);

                    return Task.FromResult(new HttpResponseMessage { StatusCode = HttpStatusCode.Found });
                });

                using (var client = new HttpClient())
                {
                    var request = new HttpRequestMessage(HttpMethod.Get, LocalHost + path);
                    var response = await client.SendAsync(request);
                    Assert.Equal(HttpStatusCode.Found, response.StatusCode);
                }
            }
        }
Exemple #36
0
 public IntegrationTests()
 {
     _host = new HttpHost("http://localhost:8080");
     _host.Add(DefaultMethodBasedCommandFactory.GetCommandsFor(typeof(Controller)));
     _host.Open();
 }
        public void Dispose()
        {
            if (_httpHost != null)
            {
                ((IDisposable)_httpHost).Dispose();
                _httpHost = null;
            }

            if (_webHookReceiverManager != null)
            {
                ((IDisposable)_webHookReceiverManager).Dispose();
                _webHookReceiverManager = null;
            }
        }
        private async Task EnsureServerOpen()
        {
            // On startup all WebHook listeners will call into this function.
            // We only need to create the server once - it is shared by all.
            if (_httpHost == null)
            {
                _httpHost = new HttpHost(_port);
                await _httpHost.OpenAsync(OnRequest);

                _trace.Verbose(string.Format("Opened HTTP server on port {0}", _port));
            }
        }
 public void Dispose()
 {
     if (_httpHost != null)
     {
         ((IDisposable)_httpHost).Dispose();
         _httpHost = null;
     }
 }