상속: IDisposable
 /// <summary>
 /// Creates an instance of the SplunkViaHttp context
 /// </summary>
 public SplunkContext(SplunkClient.Scheme scheme, string host, int port, string index, string username, string password, TimeSpan timeout, HttpMessageHandler handler, bool disposeHandler = true)
     : base(scheme, host, port, timeout, handler, disposeHandler)
 {
     Index = index;
     Username = username;
     Password = password;
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="SumoLogicAppender"/> class.
 /// </summary>
 /// <param name="log">The log service.</param>
 /// <param name="httpMessageHandler">The HTTP message handler.</param>
 public SumoLogicAppender(SumoLogic.Logging.Common.Log.ILog log, HttpMessageHandler httpMessageHandler)
 {
     this.SourceName = "Log4Net-SumoObject";
     this.ConnectionTimeout = 60000;
     this.LogLog = log ?? new DummyLog();
     this.HttpMessageHandler = httpMessageHandler;
 }
 public VkGroupMembersProvider(HttpMessageHandler httpMessageHandler, TimeSpan? maxIntervalBetweenApiRequest = null)
 {
     _httpMessageHandler = httpMessageHandler;
     _maxIntervalBetweenApiRequest = maxIntervalBetweenApiRequest >= MaxIntervalBetweenApiRequestDefault
         ? maxIntervalBetweenApiRequest.Value
         : MaxIntervalBetweenApiRequestDefault;
 }
        /// <summary>
        /// Downloads an image at the provided URL and converts it to a valid Data Uri scheme (https://en.wikipedia.org/wiki/Data_URI_scheme)
        /// </summary>
        /// <param name="url">The url where the image is located.</param>
        /// <param name="logger">A logger.</param>
        /// <param name="fallbackFileInfo">A FileInfo to retrieve the local fallback image.</param>
        /// <param name="fallbackMediaType">The media type of the fallback image.</param>
        /// <param name="messageHandler">An optional message handler.</param>
        /// <returns>A string that contains the data uri of the downloaded image, or a default image on any error.</returns>
        public static async Task<string> DownloadImageAndConvertToDataUri(this string url, ILogger logger, IFileInfo fallbackFileInfo, string fallbackMediaType = "image/png", HttpMessageHandler messageHandler = null)
        {
            // exclude completely invalid URLs
            if (!string.IsNullOrWhiteSpace(url))
            {
                try
                {
                    // set a timeout to 10 seconds to avoid waiting on that forever
                    using (var client = new HttpClient(messageHandler) { Timeout = TimeSpan.FromSeconds(10) })
                    {
                        var response = await client.GetAsync(url);
                        response.EnsureSuccessStatusCode();

                        // set the media type and default to JPG if it wasn't provided
                        string mediaType = response.Content.Headers.ContentType?.MediaType;
                        mediaType = string.IsNullOrWhiteSpace(mediaType) ? "image/jpeg" : mediaType;

                        // return the data URI according to the standard
                        return (await response.Content.ReadAsByteArrayAsync()).ToDataUri(mediaType);
                    }
                }
                catch (Exception ex)
                {
                    logger.LogInformation(0, ex, "Error while downloading resource");
                }
            }

            // any error or invalid URLs just return the default data uri
            return await fallbackFileInfo.ToDataUri(fallbackMediaType);
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="RetryHandler" /> class.
 /// </summary>
 /// <param name="innerHandler">The inner handler. (Usually new HttpClientHandler())</param>
 /// <param name="maxRetries">The maximum retries.</param>
 /// <param name="retryDelayMilliseconds">The retry delay milliseconds.</param>
 /// <param name="logger">The optional logger to log error messages to.</param>
 /// <remarks>
 /// When only the auth0 token provider is injected, the auth0 token provider should try to extract the client id from the 401 response header.
 /// </remarks>
 public RetryHandler(HttpMessageHandler innerHandler, uint maxRetries = 1, uint retryDelayMilliseconds = 500, ILogger logger = null)
     : base(innerHandler)
 {
     this.maxRetries = maxRetries;
     this.retryDelayMilliseconds = retryDelayMilliseconds;
     this.logger = logger;
 }
예제 #6
0
		public GoogleApi(string identifier, string clientId, string clientSecret, HttpMessageHandler handler = null) : base(identifier, CleanseClientId(clientId), clientSecret, handler)
		{
			this.TokenUrl = "https://accounts.google.com/o/oauth2/token";
			#if __UNIFIED__
			this.CurrentShowAuthenticator = NativeSafariAuthenticator.ShowAuthenticator; 
			#endif
		}
예제 #7
0
		public OAuthMessageHandler(HttpMessageHandler innerHandler, IHmacSha1HashProvider hashProvider, string consumerKey, string consumerSecret, Token oAuthToken)
			: base(innerHandler)
		{
            if (hashProvider == null)
                throw new ArgumentNullException("hashProvider");

			if (consumerKey == null)
				throw new ArgumentNullException("consumerKey");

			if (consumerKey.Length == 0)
				throw new ArgumentException("Consumer key cannot be empty.", "consumerKey");

			if (consumerSecret == null)
				throw new ArgumentNullException("consumerSecret");

			if (consumerSecret.Length == 0)
				throw new ArgumentException("Consumer secret cannot be empty.", "consumerSecret");

			if(oAuthToken != null && !oAuthToken.IsValid)
				throw new ArgumentException("OAuth token is not valid.", "oAuthToken");

            if (consumerKey == null)
                throw new ArgumentNullException("consumerKey");

            this.hashProvider = hashProvider;
			this.consumerKey = consumerKey;
			this.consumerSecret = consumerSecret;
			this.oAuthToken = oAuthToken;
		}
예제 #8
0
파일: HttpWrapper.cs 프로젝트: nardin/mmbot
 public HttpWrapper(string baseUrl, ILog logger, Envelope envelope, HttpMessageHandler httpMessageHandler)
 {
     _logger = logger;
     _envelope = envelope;
     _baseUrl = new Uri(baseUrl);
     _httpMessageHandler = httpMessageHandler ?? new HttpClientHandler();
 }
예제 #9
0
		protected DelegatingHandler(HttpMessageHandler innerHandler)
		{
			if (innerHandler == null)
				throw new ArgumentNullException ("innerHandler");
			
			InnerHandler = innerHandler;
		}
        /// <summary>
        /// Configures API routes to expose sensors.
        /// </summary>
        /// <param name="configuration">The HTTP configuration.</param>
        /// <param name="authorizeRequest">A delegate providing a method to authorize or deny sensor requests.</param>
        /// <param name="baseUri">The base URI at which sensors will be routed.</param>
        /// <param name="handler">An optional message handler to be invoked when sensors are called.</param>
        /// <returns>
        /// The updated <see cref="HttpConfiguration" />.
        /// </returns>
        /// <exception cref="System.ArgumentNullException">configuration
        /// or
        /// authorizeRequest</exception>
        public static HttpConfiguration MapSensorRoutes(
            this HttpConfiguration configuration,
            Func<HttpActionContext, bool> authorizeRequest,
            string baseUri = "sensors",
            HttpMessageHandler handler = null)
        {
            if (configuration == null)
            {
                throw new ArgumentNullException(nameof(configuration));
            }
            if (authorizeRequest == null)
            {
                throw new ArgumentNullException(nameof(authorizeRequest));
            }

            AuthorizeSensorsAttribute.AuthorizeRequest = authorizeRequest;

            configuration.Routes.MapHttpRoute(
                "Its-Log-Monitoring-Sensors",
                baseUri.AppendSegment("{name}"),
                defaults: new
                {
                    controller = "Sensor",
                    name = RouteParameter.Optional
                },
                constraints: null,
                handler: handler);

            return configuration;
        }
예제 #11
0
		/// <summary>
		/// Initializes a new instance of the <see cref="T:SimpleAuth.OauthApiKeyApi"/> class.
		/// </summary>
		/// <param name="identifier">This is used to store and look up credentials/cookies for the API</param>
		/// <param name="apiKey">API key.</param>
		/// <param name="authKey">Auth key.</param>
		/// <param name="authLocation">Auth location.(Header or Query)</param>
		/// <param name="authenticator">OAuth Authenticator.</param>
		/// <param name="handler">Handler.</param>
		public OauthApiKeyApi(string identifier, string apiKey, string authKey, AuthLocation authLocation , OAuthAuthenticator authenticator, HttpMessageHandler handler = null) : base(identifier, authenticator, handler)
	    {

			AuthLocation = authLocation;
			AuthKey = authKey;
		    ApiKey = apiKey;
	    }
        /// <summary>
        /// Creates an instance of an <see cref="HttpMessageHandler"/> using the <see cref="DelegatingHandler"/> instances
        /// provided by <paramref name="handlers"/>.
        /// </summary>
        /// <param name="handlers">An ordered list of <see cref="DelegatingHandler"/> instances to be invoked as an 
        /// <see cref="HttpRequestMessage"/> travels up the stack and an <see cref="HttpResponseMessage"/> travels down.</param>
        /// <param name="innerChannel">The inner channel represents the destination of the HTTP message channel.</param>
        /// <returns>The HTTP message channel.</returns>
        public static HttpMessageHandler Create(IEnumerable<DelegatingHandler> handlers, HttpMessageHandler innerChannel)
        {
            if (innerChannel == null)
            {
                throw Error.ArgumentNull("innerChannel");
            }

            if (handlers == null)
            {
                return innerChannel;
            }

            // Wire handlers up
            HttpMessageHandler pipeline = innerChannel;
            foreach (DelegatingHandler handler in handlers)
            {
                if (handler == null)
                {
                    throw Error.Argument("handlers", SRResources.DelegatingHandlerArrayContainsNullItem, typeof(DelegatingHandler).Name);
                }

                if (handler.InnerHandler != null)
                {
                    throw Error.Argument("handlers", SRResources.DelegatingHandlerArrayHasNonNullInnerHandler, typeof(DelegatingHandler).Name, "InnerHandler", handler.GetType().Name);
                }

                handler.InnerHandler = pipeline;
                pipeline = handler;
            }

            return pipeline;
        }
예제 #13
0
 protected virtual HttpClient MakeClient(HttpMessageHandler handler)
 {
     return new HttpClient(handler)
     {
         Timeout = TimeSpan.FromMilliseconds(int.MaxValue) // Longest TimeSpan HttpClient will accept
     };
 }
예제 #14
0
        /// <summary>
        /// Creates an instance of an <see cref="HttpMessageHandler"/> using the <see cref="DelegatingHandler"/> instances
        /// provided by <paramref name="handlers"/>. The resulting pipeline can be used to manually create <see cref="HttpClient"/>
        /// or <see cref="HttpMessageInvoker"/> instances with customized message handlers.
        /// </summary>
        /// <param name="innerHandler">The inner handler represents the destination of the HTTP message channel.</param>
        /// <param name="handlers">An ordered list of <see cref="DelegatingHandler"/> instances to be invoked as part 
        /// of sending an <see cref="HttpRequestMessage"/> and receiving an <see cref="HttpResponseMessage"/>.
        /// The handlers are invoked in a top-down fashion. That is, the first entry is invoked first for 
        /// an outbound request message but last for an inbound response message.</param>
        /// <returns>The HTTP message channel.</returns>
        public static HttpMessageHandler CreatePipeline(HttpMessageHandler innerHandler, IEnumerable<DelegatingHandler> handlers)
        {
            if (innerHandler == null)
            {
                throw Error.ArgumentNull("innerHandler");
            }

            if (handlers == null)
            {
                return innerHandler;
            }

            // Wire handlers up in reverse order starting with the inner handler
            HttpMessageHandler pipeline = innerHandler;
            IEnumerable<DelegatingHandler> reversedHandlers = handlers.Reverse();
            foreach (DelegatingHandler handler in reversedHandlers)
            {
                if (handler == null)
                {
                    throw Error.Argument("handlers", Properties.Resources.DelegatingHandlerArrayContainsNullItem, typeof(DelegatingHandler).Name);
                }

                if (handler.InnerHandler != null)
                {
                    throw Error.Argument("handlers", Properties.Resources.DelegatingHandlerArrayHasNonNullInnerHandler, typeof(DelegatingHandler).Name, "InnerHandler", handler.GetType().Name);
                }

                handler.InnerHandler = pipeline;
                pipeline = handler;
            }

            return pipeline;
        }
예제 #15
0
		public InstagramApi(string identifier, string clientId, string clientSecret, string redirectUrl, HttpMessageHandler handler = null)
			: base(identifier, clientId, clientSecret, handler)
		{
			this.TokenUrl = "https://api.instagram.com/oauth/access_token";
			this.RedirectUrl = new Uri(redirectUrl);
			Scopes = new[] { "basic" };
		}
        public TwitterOAuthMessageHandler(OAuthCredential oAuthCredential, OAuthSignatureEntity signatureEntity,
            TwitterQueryCollection parameters, HttpMessageHandler innerHandler)
            : base(innerHandler)
        {
            //TODO: Parameters needs to come here as encoded so that they can be encoded twice
            //      for the signature base. Handle that.

            //TODO: We don't even need to get parameters seperately. We can get them through
            //      query string and by reading the body but reading the body is a overhead here.

            _oAuthState = new OAuthState() {
                Credential = new OAuthCredentialState() {
                    ConsumerKey = oAuthCredential.ConsumerKey,
                    //encode it here first
                    CallbackUrl = OAuthUtil.PercentEncode(oAuthCredential.CallbackUrl),
                    Token = oAuthCredential.Token
                },
                SignatureEntity = new OAuthSignatureEntityState() {
                    ConsumerSecret = signatureEntity.ConsumerSecret,
                    TokenSecret = signatureEntity.TokenSecret
                },
                Parameters = parameters,
                Nonce = GenerateNonce(),
                SignatureMethod = GetOAuthSignatureMethod(),
                Timestamp = GenerateTimestamp(),
                Version = GetVersion()
            };
        }
예제 #17
0
 public AsyncClient(
     string auth,
     int timeout,
     ProductInfoHeaderValue userAgent,
     HttpMessageHandler httpMessageHandler = null
     )
 {
     _httpMessageHandler = httpMessageHandler ?? new HttpClientHandler();
     try
     {
         _httpClient = new HttpClient(_httpMessageHandler)
         {
             DefaultRequestHeaders =
             {
                 Authorization = new AuthenticationHeaderValue("Basic", auth),
                 Accept = {new MediaTypeWithQualityHeaderValue("application/json")},
                 UserAgent = {userAgent}
             },
             Timeout = TimeSpan.FromMilliseconds(timeout)
         };
     }
     catch
     {
         _httpClient?.Dispose();
         _httpMessageHandler.Dispose();
         throw;
     }
 }
        /// <summary>
        /// Initializes a new instance of the <see cref="ServerCompressionHandler" /> class.
        /// </summary>
        /// <param name="innerHandler">The inner handler.</param>
        /// <param name="contentSizeThreshold">The content size threshold before compressing.</param>
        /// <param name="enableCompression">Custom delegate to enable or disable compression.</param>
        /// <param name="compressors">The compressors.</param>
        protected BaseServerCompressionHandler(HttpMessageHandler innerHandler, int contentSizeThreshold, Predicate<HttpRequestMessage> enableCompression, params ICompressor[] compressors)
        {
            if (innerHandler != null)
            {
                this.InnerHandler = innerHandler;
            }

            this.Compressors = compressors;
            this.contentSizeThreshold = contentSizeThreshold;
            this.httpContentOperations = new HttpContentOperations();

            this.enableCompression = enableCompression ?? (x =>
            {
                // If request does not accept gzip or deflate, return false
                if (x.Headers.AcceptEncoding.All(y => y.Value != "gzip" && y.Value != "deflate"))
                {
                    return false;
                }

                // If compression has been explicitly disabled, return false
                if (x.Properties.ContainsKey("compression:Enable"))
                {
                    bool enable;
                    bool.TryParse(x.Properties["compression:Enable"].ToString(), out enable);

                    return enable;
                }

                return true;
            });
        }
 /// <summary>
 /// Used internally only for unit testing.
 /// </summary>
 /// <param name="innerHandler">The inner handler to retrieve the content from on cache misses.</param>
 /// <param name="cacheExpirationPerHttpResponseCode">A mapping of HttpStatusCode to expiration times. If unspecified takes a default value.</param>
 /// <param name="cache">The distributed cache to use.</param>
 /// /// <param name="statsProvider">An <see cref="IStatsProvider"/> that records statistic information about the caching behavior.</param>
 internal RedisCacheHandler(HttpMessageHandler innerHandler, IDictionary<HttpStatusCode, TimeSpan> cacheExpirationPerHttpResponseCode, IDistributedCache cache,
     IStatsProvider statsProvider = null) : base(innerHandler ?? new HttpClientHandler())
 {
     this.StatsProvider = statsProvider ?? new StatsProvider(nameof(RedisCacheHandler));
     this.cacheExpirationPerHttpResponseCode = cacheExpirationPerHttpResponseCode ?? new Dictionary<HttpStatusCode, TimeSpan>();
     responseCache = cache;
 }
예제 #20
0
		public Task<IHalHttpClient> CreateClientAsync(HttpMessageHandler httpMessageHandler, CachingBehavior apiRootCachingBehavior = CachingBehavior.Never)
		{
			if (httpMessageHandler == null)
				throw new ArgumentNullException(nameof(httpMessageHandler));

			return CreateHalHttpClientAsync(GetHttpClient(httpMessageHandler), apiRootCachingBehavior);
		}
 public static IAppBuilder UseWebApiWithContainer(this IAppBuilder app, HttpConfiguration configuration, HttpMessageHandler dispatcher)
 {
     IServiceProvider appContainer = app.GetApplicationContainer();
     configuration.DependencyResolver = new OwinDependencyResolverWebApiAdapter(appContainer);
     HttpServer httpServer = new OwinDependencyScopeHttpServerAdapter(configuration, dispatcher);
     return app.UseWebApi(httpServer);
 }
예제 #22
0
		public IHalHttpClient CreateClient(HttpMessageHandler httpMessageHandler)
		{
			if (httpMessageHandler == null)
				throw new ArgumentNullException(nameof(httpMessageHandler));

			return CreateHalHttpClient(GetHttpClient(httpMessageHandler));
		}
예제 #23
0
        public DurableSeqSink(
            string serverUrl,
            string bufferBaseFilename,
            string apiKey,
            int batchPostingLimit,
            TimeSpan period,
            long? bufferFileSizeLimitBytes,
            long? eventBodyLimitBytes,
            LoggingLevelSwitch levelControlSwitch,
            HttpMessageHandler messageHandler,
            long? retainedInvalidPayloadsLimitBytes)
        {
            if (serverUrl == null) throw new ArgumentNullException(nameof(serverUrl));
            if (bufferBaseFilename == null) throw new ArgumentNullException(nameof(bufferBaseFilename));

            _shipper = new HttpLogShipper(
                serverUrl, 
                bufferBaseFilename, 
                apiKey, 
                batchPostingLimit, 
                period, 
                eventBodyLimitBytes, 
                levelControlSwitch,
                messageHandler,
                retainedInvalidPayloadsLimitBytes);

            _sink = new RollingFileSink(
                bufferBaseFilename + "-{Date}.json",
                new RawJsonFormatter(),
                bufferFileSizeLimitBytes,
                null);
        }
예제 #24
0
파일: HttpClient.cs 프로젝트: LevNNN/mono
		public HttpClient (HttpMessageHandler handler, bool disposeHandler)
			: base (handler, disposeHandler)
		{
			buffer_size = int.MaxValue;
			timeout = TimeoutDefault;
			cts = new CancellationTokenSource ();
		}
 public override HttpClient CreateClient(Url url, HttpMessageHandler handler)
 {
     return new HttpClient(handler)
     {
         Timeout = FlurlHttp.Configuration.DefaultTimeout
     };
 }
    public ScApiSession(
      ISessionConfig config,
      IWebApiCredentials credentials,
      IMediaLibrarySettings mediaSettings,
      ItemSource defaultSource = null,
      HttpMessageHandler httpMessageHandler = null)
    {
      if (null == config)
      {
        throw new ArgumentNullException("ScApiSession.config cannot be null");
      }

      this.sessionConfig = config.SessionConfigShallowCopy();
      this.requestMerger = new UserRequestMerger(this.sessionConfig, defaultSource);

      if (null != credentials)
      {
        this.credentials = credentials.CredentialsShallowCopy();
      }

      if (null != mediaSettings)
      {
        this.mediaSettings = mediaSettings.MediaSettingsShallowCopy();
      }

      this.httpClient = httpMessageHandler == null ? new HttpClient() : new HttpClient(httpMessageHandler);
    }
예제 #27
0
 public OpenSrsClient(OpenSrsMode openSrsMode, string username, string apiKey, HttpMessageHandler httpMessageHandler)
 {
     HttpClient = new HttpClient(httpMessageHandler);
     OpenSrsMode = openSrsMode;
     Username = username;
     ApiKey = apiKey;
 }
예제 #28
0
		protected virtual void Dispose (bool disposing)
		{
			if (disposing && disposeHandler && handler != null) {
				handler.Dispose ();
				handler = null;
			}
		}
		//
		// Summary:
		//     Initializes an instance of a System.Net.Http.HttpMessageInvoker class with
		//     a specific System.Net.Http.HttpMessageHandler.
		//
		// Parameters:
		//   handler:
		//     The System.Net.Http.HttpMessageHandler responsible for processing the HTTP
		//     response messages.
		//
		//   disposeHandler:
		//     true if the inner handler should be disposed of by Dispose(),false if you
		//     intend to reuse the inner handler.
		public HttpMessageInvoker(HttpMessageHandler handler, bool disposeHandler)
		{
			if (handler == null)
				throw new ArgumentNullException("handler");
			m_handler = handler;
			m_disposeHandler = disposeHandler;
		}
        public IRdfeIaasClustersRestClient Create(
            HttpMessageHandler defaultHttpClientHandler,
            IHDInsightSubscriptionCredentials credentials,
            IAbstractionContext context,
            bool ignoreSslErrors)
        {
            HttpRestClientRetryPolicy retryPolicy = null;
            var tokenCreds = credentials as IHDInsightAccessTokenCredential;

            var customHandlers = new List<DelegatingHandler>();

            if (context != null && context.Logger != null)
            {
                customHandlers.Add(new HttpLoggingHandler(context.Logger));
                retryPolicy = new HttpRestClientRetryPolicy(context.RetryPolicy);
            }
            else
            {
                retryPolicy = new HttpRestClientRetryPolicy(RetryPolicyFactory.CreateExponentialRetryPolicy());
                customHandlers.Add(new HttpLoggingHandler(new Logger()));
            }

            if (tokenCreds != null)
            {
                customHandlers.Add(new BearerTokenMessageHandler(tokenCreds.AccessToken));
            }

            var httpConfiguration = new HttpRestClientConfiguration(defaultHttpClientHandler, customHandlers, retryPolicy);
            var client = new RdfeIaasClustersRestClient(credentials.Endpoint, httpConfiguration);
            return client;
        }
예제 #31
0
        /// <summary>
        /// Constructs a new instance using the specified <see cref="OAuth2Settings"/>.
        /// </summary>
        /// <param name="settings">An <see cref="OAuth2Settings"/> instance containing details used to request and manage tokens and authentication flows.</param>
        /// <param name="innerHandler">The inner <see cref="System.Net.Http.HttpMessageHandler"/> to call in the pipeline.</param>
        /// <param name="requestCondition">An optional <see cref="IRequestCondition"/> used to determine if authorisation is required. If null, then authorisation is always performed.</param>
        /// <exception cref="System.ArgumentNullException">Thrown if the <paramref name="settings"/> is null.</exception>
        /// <exception cref="System.InvalidOperationException">Thrown if a validation error occurs for the <paramref name="settings"/> argument. See <see cref="OAuth2Settings.Validate"/>.</exception>
        public OAuth2RequestSigningHandler(OAuth2Settings settings, System.Net.Http.HttpMessageHandler innerHandler, IRequestCondition requestCondition) : base(innerHandler)
        {
            if (settings == null)
            {
                throw new ArgumentNullException(nameof(settings));
            }
            settings.Validate();

            _Token            = settings.AccessToken;
            _RequestCondition = requestCondition;
            _Settings         = settings;
        }
예제 #32
0
        /// <summary>
        /// Full constructor.
        /// </summary>
        /// <param name="maxConcurrentRequests">The maximum number of concurrent requests allowed. Must be greater than zero</param>
        /// <param name="innerHandler">The next handler in the pipeline to pass the request onto.</param>
        /// <exception cref="System.ArgumentOutOfRangeException">Thrown if <paramref name="maxConcurrentRequests"/> is less than or equal to zero.</exception>
        /// <exception cref="System.ArgumentNullException">Thrown if <paramref name="innerHandler"/> parameter is null.</exception>
        public ThrottledConcurrentRequestHandler(int maxConcurrentRequests, System.Net.Http.HttpMessageHandler innerHandler) : base(innerHandler)
        {
            if (maxConcurrentRequests <= 0)
            {
                throw new ArgumentOutOfRangeException(nameof(maxConcurrentRequests));
            }
            if (innerHandler == null)
            {
                throw new ArgumentNullException(nameof(innerHandler));
            }

            _ThrottlingSemaphore = new System.Threading.Semaphore(maxConcurrentRequests, maxConcurrentRequests);
        }
예제 #33
0
        private async Task RunUsingUserCredential()
        {
            var requestUri = "path to server resource we want";

            IAuthorizationCodeFlow authFLow = null;
            var           userId            = "";
            TokenResponse token             = null;
            var           authUri           = "";

            System.Net.Http.HttpMessageHandler httpMessageHandler = null;
            var messageHandler = new ConfigurableMessageHandler(httpMessageHandler);

            var cancellationToken = new CancellationToken();

            cancellationToken.Register(() => { });

            var credential = new UserCredential(authFLow, userId, token)
            {
            };
            var accessToken = await credential.GetAccessTokenForRequestAsync(authUri, cancellationToken);

            // Create the service.
            var service = new Google.Apis.Datastore.v1beta3.DatastoreService(new BaseClientService.Initializer
            {
                HttpClientInitializer = credential,
                ApplicationName       = "Discovery Sample",
                ApiKey = "[YOUR_API_KEY_HERE]",
            });



            var httpClient = new ConfigurableHttpClient(messageHandler);

            service.HttpClientInitializer.Initialize(httpClient);

            var res = await httpClient.GetAsync(requestUri);
        }
예제 #34
0
 /// <summary>
 /// Constructs a new instance using the specified <see cref="OAuth2Settings"/>.
 /// </summary>
 /// <param name="settings">An <see cref="OAuth2Settings"/> instance containing details used to request and manage tokens and authentication flows.</param>
 /// <param name="innerHandler">The inner <see cref="System.Net.Http.HttpMessageHandler"/> to call in the pipeline.</param>
 /// <exception cref="System.ArgumentNullException">Thrown if the <paramref name="settings"/> is null.</exception>
 public OAuth2RequestSigningHandler(OAuth2Settings settings, System.Net.Http.HttpMessageHandler innerHandler) : this(settings, innerHandler, null)
 {
 }
예제 #35
0
 /// <summary>
 /// Constructs a new instance using the specified <see cref="OAuth2Settings"/>.
 /// </summary>
 /// <param name="settings">An <see cref="OAuth2Settings"/> instance containing details used to request and manage tokens and authentication flows.</param>
 /// <param name="innerHandler">The inner <see cref="System.Net.Http.HttpMessageHandler"/> to call in the pipeline.</param>
 /// <param name="requestCondition">An optional <see cref="IRequestCondition"/> used to determine if authorisation is required. If null, then authorisation is always performed.</param>
 /// <exception cref="System.ArgumentNullException">Thrown if the <paramref name="settings"/> is null.</exception>
 public OAuth2RequestSigningHandler(OAuth2Settings settings, System.Net.Http.HttpMessageHandler innerHandler, IRequestCondition requestCondition) : base(innerHandler)
 {
     Helper.Throw();
 }
 /// <summary>
 /// Full constructor.
 /// </summary>
 /// <param name="maxConcurrentRequests">The maximum number of concurrent requests allowed. Must be greater than zero</param>
 /// <param name="innerHandler">The next handler in the pipeline to pass the request onto.</param>
 /// <exception cref="System.ArgumentOutOfRangeException">Thrown if <paramref name="maxConcurrentRequests"/> is less than or equal to zero.</exception>
 /// <exception cref="System.ArgumentNullException">Thrown if <paramref name="innerHandler"/> parameter is null.</exception>
 public ThrottledConcurrentRequestHandler(int maxConcurrentRequests, System.Net.Http.HttpMessageHandler innerHandler) : base(innerHandler)
 {
     Helper.Throw();
 }
 /// <summary>
 /// Default constructor. Creates an instance that only allows 4 concurrent requests.
 /// </summary>
 /// <param name="innerHandler">The next handler in the pipeline to pass the request onto.</param>
 /// <exception cref="System.ArgumentNullException">Thrown if <paramref name="innerHandler"/> parameter is null.</exception>
 public ThrottledConcurrentRequestHandler(System.Net.Http.HttpMessageHandler innerHandler) : this(4, innerHandler)
 {
     Helper.Throw();
 }
예제 #38
0
#pragma warning disable 1998
        public static async Task Main(string[] args)
#pragma warning restore 1998
        {
            bool tracingDisabled = args.Any(arg => arg.Equals("TracingDisabled", StringComparison.OrdinalIgnoreCase));

            Console.WriteLine($"TracingDisabled {tracingDisabled}");

            string port = args.FirstOrDefault(arg => arg.StartsWith("Port="))?.Split('=')[1] ?? "9000";

            Console.WriteLine($"Port {port}");

            using (var server = WebServer.Start(port, out var url))
            {
                server.RequestHandler = HandleHttpRequests;

                Console.WriteLine();
                Console.WriteLine($"Starting HTTP listener at {url}");

                // send async http requests using HttpClient
                Console.WriteLine();
                Console.WriteLine("Sending async request with default HttpClient.");
                using (var client = new HttpClient())
                {
                    RequestHelpers.SendAsyncHttpClientRequests(client, tracingDisabled, url, RequestContent);
                }

                // send async http requests using HttpClient with CustomHandler
                Console.WriteLine();
                Console.WriteLine("Sending async request with HttpClient(CustomHandler).");
                using (var client = new HttpClient(new CustomHandler()))
                {
                    RequestHelpers.SendAsyncHttpClientRequests(client, tracingDisabled, url, RequestContent);
                }

                if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                {
                    // send async http requests using HttpClient with raw WinHttpHandler
                    Console.WriteLine();
                    Console.WriteLine("Sending async request with HttpClient(WinHttpHandler).");
                    using (var client = new HttpClient(new WinHttpHandler()))
                    {
                        RequestHelpers.SendAsyncHttpClientRequests(client, tracingDisabled, url, RequestContent);
                    }
                }

#if NETCOREAPP
                // send async http requests using HttpClient with raw SocketsHttpHandler
                Console.WriteLine();
                Console.WriteLine("Sending async request with HttpClient(SocketsHttpHandler).");
                using (var client = new HttpClient(new SocketsHttpHandler()))
                {
                    RequestHelpers.SendAsyncHttpClientRequests(client, tracingDisabled, url, RequestContent);
                }
#endif

#if NET5_0_OR_GREATER
                // send sync http requests using HttpClient
                Console.WriteLine();
                Console.WriteLine("Sending sync request with default HttpClient.");
                using (var client = new HttpClient())
                {
                    RequestHelpers.SendHttpClientRequests(client, tracingDisabled, url, RequestContent);
                }

                // send async http requests using HttpClient with CustomHandler
                Console.WriteLine();
                Console.WriteLine("Sending sync request with HttpClient(CustomHandler).");
                using (var client = new HttpClient(new CustomHandler()))
                {
                    RequestHelpers.SendHttpClientRequests(client, tracingDisabled, url, RequestContent);
                }

                // send sync http requests using HttpClient with raw SocketsHttpHandler
                Console.WriteLine();
                Console.WriteLine("Sending sync request with HttpClient(SocketsHttpHandler).");
                using (var client = new HttpClient(new SocketsHttpHandler()))
                {
                    RequestHelpers.SendHttpClientRequests(client, tracingDisabled, url, RequestContent);
                }

                // sync http requests using HttpClient are not supported with WinHttpHandler
#endif

#if NETCOREAPP2_1 || NETCOREAPP3_0 || NETCOREAPP3_1
                if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                {
                    Console.WriteLine();
                    Console.WriteLine("Sending async request with internal WinHttpHandler.");
                    Type winHttpHandler = typeof(System.Net.Http.HttpMessageHandler).Assembly.GetTypes().FirstOrDefault(t => t.Name == "WinHttpHandler");
                    System.Net.Http.HttpMessageHandler handler = (System.Net.Http.HttpMessageHandler)Activator.CreateInstance(winHttpHandler);
                    using (var invoker = new HttpMessageInvoker(handler, false))
                    {
                        await RequestHelpers.SendHttpMessageInvokerRequestsAsync(invoker, tracingDisabled, url);
                    }
                }
                else
                {
                    Console.WriteLine();
                    Console.WriteLine("Sending async request with CurlHandler.");
                    Type curlHandlerType = typeof(System.Net.Http.HttpMessageHandler).Assembly.GetTypes().FirstOrDefault(t => t.Name == "CurlHandler");
                    System.Net.Http.HttpMessageHandler handler = (System.Net.Http.HttpMessageHandler)Activator.CreateInstance(curlHandlerType);
                    using (var invoker = new HttpMessageInvoker(handler, false))
                    {
                        await RequestHelpers.SendHttpMessageInvokerRequestsAsync(invoker, tracingDisabled, url);
                    }
                }
#endif

                Console.WriteLine();
                Console.WriteLine("Stopping HTTP listener.");
            }

            // Force process to end, otherwise the background listener thread lives forever in .NET Core.
            // Apparently listener.GetContext() doesn't throw an exception if listener.Stop() is called,
            // like it does in .NET Framework.
            Environment.Exit(0);
        }
예제 #39
0
 public MobileCenterAPIServiceApiKeyApi(string apiKey, string encryptionKey, System.Net.Http.HttpMessageHandler handler = null) :
     base(apiKey, encryptionKey, "v0.1/api_tokens", handler)
 {
     BaseAddress = new System.Uri("https://api.mobile.azure.com");;
 }
 /// <summary>
 /// Full constructor.
 /// </summary>
 /// <param name="innerHandler">The next handler in the pipeline to pass requests through.</param>
 /// <param name="requestCondition">A <see cref="IRequestCondition"/> that controls whether any individual request is compressed or not. If null, all requests are compressed.</param>
 public CompressedRequestHandler(System.Net.Http.HttpMessageHandler innerHandler, IRequestCondition requestCondition) : base(innerHandler)
 {
     Helper.Throw();
 }
예제 #41
0
 /// <summary>
 /// Default constructor. Creates an instance that only allows 4 concurrent requests.
 /// </summary>
 /// <param name="innerHandler">The next handler in the pipeline to pass the request onto.</param>
 /// <exception cref="System.ArgumentNullException">Thrown if <paramref name="innerHandler"/> parameter is null.</exception>
 public ThrottledConcurrentRequestHandler(System.Net.Http.HttpMessageHandler innerHandler) : this(DefaultMaxRequests, innerHandler)
 {
 }
 /// <summary>
 /// Partial constructor.
 /// </summary>
 /// <param name="innerHandler">The next handler in the pipeline to pass requests through.</param>
 public CompressedRequestHandler(System.Net.Http.HttpMessageHandler innerHandler) : this(innerHandler, null)
 {
     Helper.Throw();
 }
예제 #43
0
 protected DelegatingHandler(HttpMessageHandler innerHandler)
 {
     InnerHandler = innerHandler;
 }
예제 #44
0
 public RetryHandler(System.Net.Http.HttpMessageHandler innerHandler, int maxRetries = 3, int timeToWait = 3000)
     : base(innerHandler)
 {
     MaxRetries = maxRetries;
     TimeToWait = timeToWait;
 }
예제 #45
0
 /// <summary>
 /// DiagnosticHandler constructor
 /// </summary>
 /// <param name="innerHandler">Inner handler: Windows or Unix implementation of HttpMessageHandler.
 /// Note that DiagnosticHandler is the latest in the pipeline </param>
 public DiagnosticsHandler(HttpMessageHandler innerHandler) : base(innerHandler)
 {
 }
 /// <summary>
 /// Full constructor.
 /// </summary>
 /// <param name="innerHandler">The next handler in the pipeline to pass requests through.</param>
 /// <param name="requestCondition">A <see cref="IRequestCondition"/> that controls whether any individual request is compressed or not. If null, all requests are compressed.</param>
 public CompressedRequestHandler(System.Net.Http.HttpMessageHandler innerHandler, IRequestCondition requestCondition) : base(innerHandler)
 {
     _RequestCondition = requestCondition;
 }
예제 #47
0
 public HttpClient(HttpMessageHandler handler)
     : this(handler, true)
 {
 }
예제 #48
0
        public RedirectHandler(int maxAutomaticRedirections, HttpMessageHandler initialInnerHandler, HttpMessageHandler redirectInnerHandler)
        {
            Debug.Assert(initialInnerHandler != null);
            Debug.Assert(redirectInnerHandler != null);
            Debug.Assert(maxAutomaticRedirections > 0);

            _maxAutomaticRedirections = maxAutomaticRedirections;
            _initialInnerHandler      = initialInnerHandler;
            _redirectInnerHandler     = redirectInnerHandler;
        }
예제 #49
0
 protected MessageProcessingHandler(HttpMessageHandler innerHandler)
     : base(innerHandler)
 {
 }
예제 #50
0
        public AuthenticateAndRedirectHandler(bool preAuthenticate, ICredentials credentials, bool allowRedirect, int maxAutomaticRedirections, HttpMessageHandler innerHandler)
        {
            Debug.Assert(innerHandler != null);

            _preAuthenticate = preAuthenticate;
            _credentials     = credentials;
            _allowRedirect   = allowRedirect;

            if (allowRedirect && maxAutomaticRedirections < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(maxAutomaticRedirections));
            }

            _maxAutomaticRedirections = maxAutomaticRedirections;
            _innerHandler             = innerHandler;
        }