当前位置: 首页>>代码示例>>C#>>正文


C# HttpBaseProtocolFilter类代码示例

本文整理汇总了C#中HttpBaseProtocolFilter的典型用法代码示例。如果您正苦于以下问题:C# HttpBaseProtocolFilter类的具体用法?C# HttpBaseProtocolFilter怎么用?C# HttpBaseProtocolFilter使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


HttpBaseProtocolFilter类属于命名空间,在下文中一共展示了HttpBaseProtocolFilter类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: InvalidateAsync

        public async Task InvalidateAsync()
        {
            EncodeCredentials();

            var req = new HttpRequestMessage(HttpMethod.Post, new Uri(OAuth2InvalidateToken));
            req.Headers.Add("Authorization", "Basic " + BasicToken);
            req.Headers.Add("User-Agent", UserAgent);
            req.Headers.Add("Expect", "100-continue");
            req.Content = new HttpStringContent("access_token=" + BearerToken, Windows.Storage.Streams.UnicodeEncoding.Utf8, "application/x-www-form-urlencoded");

            var baseFilter = new HttpBaseProtocolFilter
            {
                AutomaticDecompression = true
            };

            //var handler = new HttpClientHandler();
            //if (handler.SupportsAutomaticDecompression)
            //    handler.AutomaticDecompression = DecompressionMethods.GZip;
            //if (Proxy != null && handler.SupportsProxy)
            //    handler.Proxy = Proxy;

            using (var client = new HttpClient(baseFilter))
            {
                var msg = await client.SendRequestAsync(req);

                await TwitterErrorHandler.ThrowIfErrorAsync(msg);

                string response = await msg.Content.ReadAsStringAsync();

                var responseJson = JsonMapper.ToObject(response);
                BearerToken = responseJson.GetValue<string>("access_token"); 
            }
        }
开发者ID:neilhighley,项目名称:LinqToTwitter,代码行数:33,代码来源:ApplicationOnlyAuthorizer.cs

示例2: GetBearerTokenAsync

        async Task GetBearerTokenAsync()
        {
            var req = new HttpRequestMessage(HttpMethod.Post, new Uri(OAuth2Token));
            req.Headers.Add("Authorization", "Basic " + BasicToken);
            req.Headers.Add("User-Agent", UserAgent);
            req.Headers.Add("Expect", "100-continue");
            req.Content = new HttpStringContent("grant_type=client_credentials", Windows.Storage.Streams.UnicodeEncoding.Utf8, "application/x-www-form-urlencoded");

            var baseFilter = new HttpBaseProtocolFilter
            {
                AutomaticDecompression = SupportsCompression,
                ProxyCredential = ProxyCredential,
                UseProxy = UseProxy
            };

            using (var client = new HttpClient(baseFilter))
            {
                var msg = await client.SendRequestAsync(req);

                await TwitterErrorHandler.ThrowIfErrorAsync(msg);

                string response = await msg.Content.ReadAsStringAsync();

                var responseJson = JsonMapper.ToObject(response);
                BearerToken = responseJson.GetValue<string>("access_token"); 
            }
        }
开发者ID:prog-moh,项目名称:LinqToTwitter,代码行数:27,代码来源:ApplicationOnlyAuthorizer.cs

示例3: OnNavigatedTo

 protected override void OnNavigatedTo(NavigationEventArgs e)
 {
     HttpBaseProtocolFilter baseProtocolFilter = new HttpBaseProtocolFilter();
     meteredConnectionFilter = new HttpMeteredConnectionFilter(baseProtocolFilter);
     httpClient = new HttpClient(meteredConnectionFilter);
     cts = new CancellationTokenSource();
 }
开发者ID:t-angma,项目名称:Windows-universal-samples,代码行数:7,代码来源:scenario12_meteredconnectionfilter.xaml.cs

示例4: btnExecuta_Click

        private async void btnExecuta_Click(object sender, RoutedEventArgs e)
        {

            HttpBaseProtocolFilter Filtro = new HttpBaseProtocolFilter();
            Filtro.CacheControl.ReadBehavior = Windows.Web.Http.Filters.HttpCacheReadBehavior.MostRecent;
            Filtro.CacheControl.WriteBehavior = Windows.Web.Http.Filters.HttpCacheWriteBehavior.NoCache;

            var httpClient = new HttpClient(Filtro);
            httpClient.BaseAddress = new Uri("http://192.168.25.80/");            
            
            //httpClient.Timeout = TimeSpan.FromMinutes(1);
            httpClient.Timeout = TimeSpan.FromSeconds(3);
            //httpClient.Timeout = TimeSpan.FromMilliseconds(200);

            try
            {
                var Resposta = httpClient.GetAsync("").Result;
                if (Resposta.IsSuccessStatusCode)
                {
                    lblResultado.Text = Resposta.Content.ReadAsStringAsync().Result.ToString();
HttpBaseProtocolFilter
                }
            }
            catch (HttpRequestException)
            {
                lblResultado.Text = "Servidor Não Disponível";
            }

            catch (TimeoutException)
            {
                lblResultado.Text = "Tempo Expirado";
            }
        }
开发者ID:trilok567,项目名称:Windows-Phone,代码行数:33,代码来源:MainPage.xaml.cs

示例5: GetCookies_Click

        private void GetCookies_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                // 'AddressField' is a disabled text box, so the value is considered trusted input. When enabling the
                // text box make sure to validate user input (e.g., by catching FormatException as shown in scenario 1).
                Uri uri = new Uri(AddressField.Text);

                HttpBaseProtocolFilter filter = new HttpBaseProtocolFilter();
                HttpCookieCollection cookieCollection = filter.CookieManager.GetCookies(uri);

                OutputField.Text = cookieCollection.Count + " cookies found.\r\n";
                foreach (HttpCookie cookie in cookieCollection)
                {
                    OutputField.Text += "--------------------\r\n";
                    OutputField.Text += "Name: " + cookie.Name + "\r\n";
                    OutputField.Text += "Domain: " + cookie.Domain + "\r\n";
                    OutputField.Text += "Path: " + cookie.Path + "\r\n";
                    OutputField.Text += "Value: " + cookie.Value + "\r\n";
                    OutputField.Text += "Expires: " + cookie.Expires + "\r\n";
                    OutputField.Text += "Secure: " + cookie.Secure + "\r\n";
                    OutputField.Text += "HttpOnly: " + cookie.HttpOnly + "\r\n";
                }
            }
            catch (Exception ex)
            {
                rootPage.NotifyUser("Error: " + ex.Message, NotifyType.ErrorMessage);
            }
        }
开发者ID:mbin,项目名称:Win81App,代码行数:29,代码来源:Scenario9.xaml.cs

示例6: receive_file

        public override async void receive_file(String devicename, String add, int not)
        {
            try
            {
                _httpurl = new Uri(add);
                _httpprogress = new Progress<HttpProgress>(ProgressHandler);

                HttpRequestMessage request = new HttpRequestMessage(new HttpMethod("GET"), _httpurl);
                                
                HttpBaseProtocolFilter filter = new HttpBaseProtocolFilter();
                filter.CacheControl.ReadBehavior = HttpCacheReadBehavior.MostRecent;
                filter.CacheControl.WriteBehavior = HttpCacheWriteBehavior.NoCache;

                _httpclient = new HttpClient(filter);

                _cancel_token_source = new CancellationTokenSource();
                _cancel_token = _cancel_token_source.Token;

                scan_network_speed();
                _stopwatch.Start();

                _httpresponse = await _httpclient.SendRequestAsync(request).AsTask(_cancel_token, _httpprogress);

                StorageFolder folder = KnownFolders.PicturesLibrary;
                StorageFile file = await folder.CreateFileAsync(this.filepath, CreationCollisionOption.ReplaceExisting);
                IRandomAccessStream filestream = await file.OpenAsync(FileAccessMode.ReadWrite);
                IOutputStream filewriter = filestream.GetOutputStreamAt(0);
                _datawriter = new DataWriter(filewriter);

                _timer.Cancel();

                _transferspeed /= 1024;
                _message = format_message(_stopwatch.Elapsed, "Transferspeed", _transferspeed.ToString(), " kB/s");
                this.callback.on_transfer_speed_change(_message, this.results);
                this.main_view.text_to_logs(_message.Replace("\t", " "));

                _stopwatch.Stop();

                _buffer = await _httpresponse.Content.ReadAsBufferAsync();

                _datawriter.WriteBuffer(_buffer);
                await _datawriter.StoreAsync();

                _datawriter.Dispose();
                filewriter.Dispose();
                filestream.Dispose();

                _httpresponse.Content.Dispose();
                _httpresponse.Dispose();
                _httpclient.Dispose();

                _message = format_message(_stopwatch.Elapsed, "File Transfer", "OK", this.filepath);
                this.callback.on_file_received(_message, this.results);
                this.main_view.text_to_logs(_message.Replace("\t", " "));
            }
            catch (Exception e)
            {
                append_error_tolog(e, _stopwatch.Elapsed, "");
            }            
        }
开发者ID:StabilityofWT,项目名称:Stability-Monitor,代码行数:60,代码来源:Gsm_agent.cs

示例7: MainPage

        public MainPage()
        {
            this.InitializeComponent();

            filter = new HttpBaseProtocolFilter();
            filter.CacheControl.ReadBehavior = HttpCacheReadBehavior.MostRecent;
            httpClient = new HttpClient(filter);

            string username = "admin";
            string password = "admin";
            var buffer = Windows.Security.Cryptography.CryptographicBuffer.ConvertStringToBinary(username + ":" + password, Windows.Security.Cryptography.BinaryStringEncoding.Utf8);
            string base64token = Windows.Security.Cryptography.CryptographicBuffer.EncodeToBase64String(buffer);
            HttpCredentialsHeaderValue authHeader = new HttpCredentialsHeaderValue("Basic", base64token);

//            var ah = new HttpCredentialsHeaderValue("Authentication", "Basic YWRtaW46YWRtaW4=")
            httpClient.DefaultRequestHeaders.Authorization = authHeader;

// Took some time to figure out a "bug"? when using "deflate" which is default...
            //            httpClient.DefaultRequestHeaders.Add("Accept-Encoding", "deflate");   //Problem here...
            httpClient.DefaultRequestHeaders.Add("Accept-Encoding", "gzip");
//            httpClient.DefaultRequestHeaders.Add("Accept-Encoding", "");

                // We're not using this at the moment...
            cts = new CancellationTokenSource();
        }
开发者ID:bk147,项目名称:ZWaveTests,代码行数:25,代码来源:MainPage.xaml.cs

示例8: Execute

        public async void Execute(string token, string content)
        {
            Uri uri = new Uri(API_ADDRESS + path);

            var rootFilter = new HttpBaseProtocolFilter();

            rootFilter.CacheControl.ReadBehavior = Windows.Web.Http.Filters.HttpCacheReadBehavior.MostRecent;
            rootFilter.CacheControl.WriteBehavior = Windows.Web.Http.Filters.HttpCacheWriteBehavior.NoCache;

            HttpClient client = new HttpClient(rootFilter);
            //client.DefaultRequestHeaders.Add("timestamp", DateTime.Now.ToString());
            if(token != null)
                client.DefaultRequestHeaders.Add("x-access-token", token);

            System.Threading.CancellationTokenSource source = new System.Threading.CancellationTokenSource(2000);

            HttpResponseMessage response = null;
            if (requestType == GET)
            {
                try
                {
                    response = await client.GetAsync(uri).AsTask(source.Token);
                }
                catch (TaskCanceledException)
                {
                    response = null;
                }

            }else if (requestType == POST)
            {
                HttpRequestMessage msg = new HttpRequestMessage(new HttpMethod("POST"), uri);
                if (content != null)
                {
                    msg.Content = new HttpStringContent(content);
                    msg.Content.Headers.ContentType = new HttpMediaTypeHeaderValue("application/json");
                }

                try
                {
                    response = await client.SendRequestAsync(msg).AsTask(source.Token);
                }
                catch (TaskCanceledException)
                {
                    response = null;
                }
            }

            if (response == null)
            {
                if (listener != null)
                    listener.onTaskCompleted(null, requestCode);
            }
            else
            {
                string answer = await response.Content.ReadAsStringAsync();

                if(listener != null)
                    listener.onTaskCompleted(answer, requestCode);
            }
        }
开发者ID:francisco-maciel,项目名称:FEUP-CMOV_StockQuotes,代码行数:60,代码来源:APIRequest.cs

示例9: SendRequest

        public async Task<bool> SendRequest()
        {
            try
            {
                var config = new ConfigurationViewModel();
                var uri = new Uri(config.Uri + _path);

                var filter = new HttpBaseProtocolFilter();
                if (config.IsSelfSigned == true)
                {
                    filter.IgnorableServerCertificateErrors.Add(ChainValidationResult.Untrusted);
                    filter.IgnorableServerCertificateErrors.Add(ChainValidationResult.InvalidName);
                }

                var httpClient = new HttpClient(filter);
                httpClient.DefaultRequestHeaders.Accept.Clear();
                httpClient.DefaultRequestHeaders.Accept.Add(new HttpMediaTypeWithQualityHeaderValue("text/plain"));
                httpClient.DefaultRequestHeaders.UserAgent.Add(new HttpProductInfoHeaderValue(new HttpProductHeaderValue("Mozilla", "5.0").ToString()));
                httpClient.DefaultRequestHeaders.UserAgent.Add(new HttpProductInfoHeaderValue(new HttpProductHeaderValue("Firefox", "26.0").ToString()));

                var reponse = await httpClient.GetAsync(uri);
                httpClient.Dispose();
                return reponse.IsSuccessStatusCode;
            }
            catch (Exception)
            {
                return false;
            }
        }
开发者ID:phabrys,项目名称:Domojee,代码行数:29,代码来源:HttpRpcClient.cs

示例10: GetCookies_Click

        private void GetCookies_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                Uri resourceAddress;
                if (!Helpers.TryGetUri(AddressField.Text, out resourceAddress))
                {
                    rootPage.NotifyUser("Invalid URI.", NotifyType.ErrorMessage);
                    return;
                }

                HttpBaseProtocolFilter filter = new HttpBaseProtocolFilter();
                HttpCookieCollection cookieCollection = filter.CookieManager.GetCookies(resourceAddress);

                OutputField.Text = cookieCollection.Count + " cookies found.\r\n";
                foreach (HttpCookie cookie in cookieCollection)
                {
                    OutputField.Text += "--------------------\r\n";
                    OutputField.Text += "Name: " + cookie.Name + "\r\n";
                    OutputField.Text += "Domain: " + cookie.Domain + "\r\n";
                    OutputField.Text += "Path: " + cookie.Path + "\r\n";
                    OutputField.Text += "Value: " + cookie.Value + "\r\n";
                    OutputField.Text += "Expires: " + cookie.Expires + "\r\n";
                    OutputField.Text += "Secure: " + cookie.Secure + "\r\n";
                    OutputField.Text += "HttpOnly: " + cookie.HttpOnly + "\r\n";
                }
            }
            catch (Exception ex)
            {
                rootPage.NotifyUser("Error: " + ex.Message, NotifyType.ErrorMessage);
            }
        }
开发者ID:RasmusTG,项目名称:Windows-universal-samples,代码行数:32,代码来源:Scenario9_GetCookie.xaml.cs

示例11: InitializeContextForWebViews

        /// <summary>
        /// Moves needed cookies to globaly used client by WebViews control, web view authentication in other words.
        /// </summary>
        /// <returns></returns>
        public static async Task InitializeContextForWebViews(bool mobile)
        {
            if (_webViewsInitialized)
                return;
            _webViewsInitialized = true;

            var filter = new HttpBaseProtocolFilter();
            var httpContext = await MalHttpContextProvider.GetHttpContextAsync();
            var cookies = httpContext.Handler.CookieContainer.GetCookies(new Uri(MalHttpContextProvider.MalBaseUrl));
            if (mobile)
            {
                filter.CookieManager.SetCookie(new HttpCookie("view", "myanimelist.net", "/") { Value = "sp" });
            }
            foreach (var cookie in cookies.Cast<Cookie>())
            {
                try
                {
                    var newCookie = new HttpCookie(cookie.Name, cookie.Domain, cookie.Path) { Value = cookie.Value };
                    filter.CookieManager.SetCookie(newCookie);
                }
                catch (Exception)
                {
                    var msg = new MessageDialog( "Authorization failed while rewriting cookies, I don't know why this is happenning and after hours of debugging it fixed itself after reinstall. :(","Something went wrong™");
                    await msg.ShowAsync();
                }

            }

            filter.AllowAutoRedirect = true;
            Windows.Web.Http.HttpClient client = new Windows.Web.Http.HttpClient(filter); //use globaly by webviews
        }
开发者ID:Mordonus,项目名称:MALClient,代码行数:35,代码来源:MalWebViewHttpContextInitializer.cs

示例12: Get

        protected string Get(string partUrl)
        {
            using (var filter = new HttpBaseProtocolFilter())
            {
                filter.IgnorableServerCertificateErrors.Add(Windows.Security.Cryptography.Certificates.ChainValidationResult.Expired);                               
                filter.IgnorableServerCertificateErrors.Add(Windows.Security.Cryptography.Certificates.ChainValidationResult.InvalidName);
                filter.IgnorableServerCertificateErrors.Add(Windows.Security.Cryptography.Certificates.ChainValidationResult.Untrusted);
                

                using (var wc = new HttpClient(filter))
                {
                    bool completed = false;
                    var url = BuildUrl(partUrl);
                    var task = wc.GetStringAsync(url);

                    task.Completed = delegate { completed = true; };

                    while (!completed)
                    {
                        Task.Delay(200).Wait();
                    }

                    var content = task.GetResults();

                    return content.TrimWhiteSpaceAndQuotes();
                }
            }
        }
开发者ID:Toolbastler,项目名称:PrtgViewer,代码行数:28,代码来源:PrtgWebClientBase.cs

示例13: LoadFlickrPhotosAsync

    public async Task LoadFlickrPhotosAsync(string feedUrl)
    {
      Photos.Clear();

      var filter = new HttpBaseProtocolFilter();
      var client = new HttpClient(filter);
      var respText = await client.GetStringAsync(new Uri(feedUrl));

      // safe check
      respText = respText.Replace("\'", "\\'");

      // process respText
      JsonObject jsonObject = JsonObject.Parse(respText);
      JsonArray jsonArray = jsonObject["items"].GetArray();

      foreach (JsonValue val in jsonArray)
      {
        JsonObject item = val.GetObject();

        Photos.Add(new PhotoItem()
        {
          Title = item["title"].GetString(),
          Link = item["link"].GetString(),
          PhotoUrl = item["media"].GetObject()["m"].GetString()
        });

      }
    }
开发者ID:liqinghuang,项目名称:UWPBootCamp,代码行数:28,代码来源:MainViewModel.cs

示例14: HttpGet

        public static async Task<string> HttpGet(string uri)
        {


            if (Config.IsNetWork)
            {
                NotifyControl notify = new NotifyControl();
                notify.Text = "亲,努力加载中...";
                notify.Show();
             
                var _filter = new HttpBaseProtocolFilter();
                using (HttpClient httpClient = new HttpClient(_filter))
                {

                    _filter.CacheControl.WriteBehavior = HttpCacheWriteBehavior.NoCache;
                    HttpResponseMessage response = new HttpResponseMessage();
                    response = await httpClient.GetAsync(new Uri(uri, UriKind.Absolute));
                    responseString = await response.Content.ReadAsStringAsync();
                    notify.Hide();

                }

            }
            return responseString;



        }
开发者ID:x01673,项目名称:dreaming,代码行数:28,代码来源:HttpGetNoCache.cs

示例15: GetHttpClient

 internal static HttpClient GetHttpClient()
 {
     var filter = new HttpBaseProtocolFilter() { AllowAutoRedirect = false, AutomaticDecompression = true };
     var client = new HttpClient(filter);
     
     return client;
 }
开发者ID:vinhlehp90,项目名称:VimaruUWP,代码行数:7,代码来源:Utils.cs


注:本文中的HttpBaseProtocolFilter类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。