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


C# WebClient.UploadValuesAsync方法代码示例

本文整理汇总了C#中System.Net.WebClient.UploadValuesAsync方法的典型用法代码示例。如果您正苦于以下问题:C# WebClient.UploadValuesAsync方法的具体用法?C# WebClient.UploadValuesAsync怎么用?C# WebClient.UploadValuesAsync使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.Net.WebClient的用法示例。


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

示例1: SendNotifications

        internal static void SendNotifications(IEnumerable<string> apiKeys, string application, string header, string message)
        {
            var data = new NameValueCollection();
            data["AuthorizationToken"] = "";
            data["Body"] = message;
            data["IsImportant"] = IsImportant;
            data["IsSilent"] = IsSilent;
            data["Source"] = application;
            data["TimeToLive"] = TimeToLive;
            data["Title"] = header;
            if (!Validate(data))
            {
                return;
            }

            foreach (var apiKey in apiKeys)
            {
                using (var client = new WebClient())
                {
                    data.Set("AuthorizationToken", apiKey);

                    client.Headers[HttpRequestHeader.ContentType] = RequestContentType;
                    client.UploadValuesAsync(new Uri(RequestUrl), data);
                }
            }
        }
开发者ID:Giecha,项目名称:AlarmWorkflow,代码行数:26,代码来源:Pushalot.cs

示例2: Upload

        public override bool Upload(UploadService activeService, ExtendedScreenshot screenshot)
        {
            if (InProgress)
                return false;

            Trace.WriteLine("Starting upload process...", string.Format("FormsUploader.Upload [{0}]", System.Threading.Thread.CurrentThread.Name));

            this.ActiveService = activeService;
            this.InProgress = true;
            OnUploadStarted(new EventArgs());

            try
            {
                using (var wc = new WebClient())
                {
                    wc.UploadProgressChanged += UploadProgressChanged;
                    wc.UploadValuesCompleted += UploadValuesCompleted;

                    var bg = new BackgroundWorker();
                    bg.DoWork += (o, a) =>
                        {
                            Trace.WriteLine("Starting stream conversion... ", string.Format("FormsUploader.Upload.DoWork [{0}]", System.Threading.Thread.CurrentThread.Name));

                            var ImageData = string.Empty;
                            using (var ms = screenshot.EditedScreenshotPNGImageStream())
                                ImageData = Convert.ToBase64String(ms.ToArray());

                            var CurrentUploadValues = new NameValueCollection();
                            foreach (var k in activeService.UploadValues.AllKeys.ToList())
                                CurrentUploadValues.Add(k, activeService.UploadValues[k].Replace("%i", ImageData));

                            Trace.WriteLine("Stream conversion complete.", string.Format("FormsUploader.Upload.DoWork [{0}]", System.Threading.Thread.CurrentThread.Name));
                            Trace.WriteLine("Starting async upload...", string.Format("FormsUploader.Upload.DoWork [{0}]", System.Threading.Thread.CurrentThread.Name));

                            wc.UploadValuesAsync(new Uri(activeService.EndpointUrl), CurrentUploadValues);

                            Trace.WriteLine("Upload start complete.", string.Format("FormsUploader.Upload.DoWork [{0}]", System.Threading.Thread.CurrentThread.Name));
                        };
                    bg.RunWorkerAsync();
                }

                return true;
            }
            catch (Exception ex)
            {
                Trace.WriteLine(string.Format("Exception occurred during upload: {0}", ex.GetBaseException()), string.Format("FormsUploader.Upload [{0}]", System.Threading.Thread.CurrentThread.Name));

                InProgress = false;
                OnUploadEnded(new UploaderEndedEventArgs(ex.GetBaseException()));

                return false;
            }
        }
开发者ID:sevenflowenol,项目名称:ProSnap,代码行数:53,代码来源:FormsUploader.cs

示例3: ConnectDatabase

        public ConnectDatabase(string Email, string Password)
        {
            WebClient client = new WebClient();
            Uri uri = new Uri("http://192.168.100.12/php/includes/process_login_android.php");
            Uri localUri = new Uri("http://localhost/php/android_api.php");
            NameValueCollection parameters = new NameValueCollection();

            parameters.Add("Email", Email);
            parameters.Add("Password", Password);

            client.UploadValuesCompleted += client_UploadValuesCompleted;
            client.UploadValuesAsync(uri, parameters);
        }
开发者ID:Alexander144,项目名称:PJ3100Gruppe20GIT,代码行数:13,代码来源:ConnectDatabase.cs

示例4: RefreshOnlineStatus

 private void RefreshOnlineStatus()
 {
     try
     {
         using (var client = new WebClient())
         {
             var data = new NameValueCollection();
             client.UploadValuesAsync(refreshUri, "POST", data);
         }
     }
     catch (Exception ex)
     {
         Logger.Log("Error refreshing online status in PoeTradeOnlineHelper: " + ex.ToString());
     }
 }
开发者ID:BlueManiac,项目名称:Procurement,代码行数:15,代码来源:PoeTradeOnlineHelper.cs

示例5: RefreshOnlineStatus

        private void RefreshOnlineStatus()
        {
            try
            {
                // Trigger the online signal again when we are about to expire with poe.trade
                var timeSinceLastOnline = DateTime.Now - lastOnlineTime;
                if (timeSinceLastOnline.Minutes > 55)
                {
                    currentlyOnline = false;
                }

                Func<Process, bool> IsPoE = (c => c.MainWindowTitle.Contains("Path of Exile") || c.ProcessName.Contains("PathOfExile"));
                var idleTime = GetIdleTime();

                if (idleTime >= TimeSpan.FromMinutes(10) || !Process.GetProcesses().Any(IsPoE))
                {
                    // Prevent from spamming poe.trade
                    if (currentlyOnline)
                    {
                        using (var client = new WebClient())
                        {
                            var offlineUri = new Uri(refreshUri.OriginalString + "/offline");
                            var data = new NameValueCollection();
                            client.UploadValuesAsync(offlineUri, "POST", data);
                        }
                    }

                    // User is AFK or PoE is not running.
                    currentlyOnline = false;
                    return;
                }

                if (!currentlyOnline)
                {
                    using (var client = new WebClient())
                    {
                        var data = new NameValueCollection();
                        client.UploadValuesAsync(refreshUri, "POST", data);
                        currentlyOnline = true;
                        lastOnlineTime = DateTime.Now;
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Log("Error refreshing online/offline status in PoeTradeOnlineHelper: " + ex.ToString());
            }
        }
开发者ID:yazilliclick,项目名称:Procurement,代码行数:48,代码来源:PoeTradeOnlineHelper.cs

示例6: SendNotification

        public static void SendNotification(string message, string title, NotificationType type = NotificationType.Info, string notificationUrl = "")
        {
            var url = string.Format("http://{0}:{1}/api/notification", Host, Port);
            var uri = new Uri(url);

            using (var webClient = new WebClient())
            {
                webClient.Credentials = CredentialCache.DefaultNetworkCredentials;
                webClient.UploadValuesAsync(uri, "POST", new NameValueCollection{
                    {"message", message},
                    {"title", title},
                    {"type", GetNotificationType(type)},
                    {"url", notificationUrl}
                });
            }
        }
开发者ID:rcbdev,项目名称:Notifications,代码行数:16,代码来源:NotifcationSender.cs

示例7: PostToImgur

 public void PostToImgur(Image image, UISystem.UIButton button)
 {
     uploadButton = button;
     var stream = new MemoryStream();
     image.Save(stream, ImageFormat.Png);
     var inArray = stream.GetBuffer();
     using (var client = new WebClient())
     {
         client.UploadProgressChanged += w_UploadProgressChanged;
         client.UploadValuesCompleted += w_UploadValuesCompleted;
         var values2 = new NameValueCollection();
         values2.Add("key", "eeb1018be96322f46df76ceb36576e08");
         values2.Add("image", Convert.ToBase64String(inArray));
         var data = values2;
         client.UploadValuesAsync(new Uri("http://imgur.com/api/upload.xml"), data);
     }
 }
开发者ID:LoveLeAnon,项目名称:Summit-Client,代码行数:17,代码来源:PreviewScreenshot.cs

示例8: PostToImgur

 public void PostToImgur(string filename)
 {
     changeValueEnabled();
     Bitmap bitmap = new Bitmap(filename);
     MemoryStream memoryStream = new MemoryStream();
     bitmap.Save(memoryStream, ImageFormat.Jpeg);
     using (var w = new WebClient())
     {
         w.UploadProgressChanged += new UploadProgressChangedEventHandler(delegate(object send, UploadProgressChangedEventArgs arg)
             {
                 int percent = arg.ProgressPercentage;
                 progressBar.Value = percent > 0 ? (percent < 45 ? percent * 2 : (percent >= 90 ? percent : 90)) : 0;
             });
         this.FormClosing += new FormClosingEventHandler(delegate(object send, FormClosingEventArgs arg)
             {
                 w.CancelAsync();
             });
         var values = new NameValueCollection
         {
             { "key", IMGUR_API_KEY },
             { "image", Convert.ToBase64String(memoryStream.ToArray()) }
         };
         string debug = values.ToString();
         byte[] response = new byte[0];
         w.UploadValuesCompleted += new UploadValuesCompletedEventHandler(delegate(object send, UploadValuesCompletedEventArgs arg)
         {
             if (arg.Cancelled) return;
             response = arg.Result;
             XDocument xDocument = XDocument.Load(new MemoryStream(response));
             bitmap.Dispose();
             _address = (string)xDocument.Root.Element("original_image");
             this.Close();
         });
         w.UploadValuesAsync(new Uri("http://imgur.com/api/upload.xml"), values);
         buttonClose.Click -= buttonClose_Click;
         buttonClose.Click += new EventHandler(delegate(object send, EventArgs arg)
             {
                 w.CancelAsync();
                 changeValueEnabled();
                 buttonClose.Click += buttonClose_Click;
             });
     }
 }
开发者ID:ulmic,项目名称:MIC_Enterprise,代码行数:43,代码来源:SelectImage.cs

示例9: PushFeed

        public HttpStatusCode PushFeed(string xml, string gsaHost, bool async)
        {
            using (var client = new WebClient())
            {
                var values = new NameValueCollection();
                values["feedtype"] = "incremental";
                values["datasource"] = "web";
                values["data"] = xml;

                try
                {
                    if (async)
                    {
                        client.UploadValuesAsync(new Uri(string.Format("{0}:19900/xmlfeed", gsaHost)), values);
                    }
                    else
                    {
                        client.UploadValues(new Uri(string.Format("{0}:19900/xmlfeed", gsaHost)), values);
                    }
                }
                catch (WebException wex)
                {
                    if (wex.Status == WebExceptionStatus.ProtocolError)
                    {
                        var response = wex.Response as HttpWebResponse;
                        if (response != null)
                        {
                            return response.StatusCode;
                        }
                    }
                    return HttpStatusCode.InternalServerError;
                }
                catch (Exception ex)
                {
                    return HttpStatusCode.InternalServerError;
                }

                return HttpStatusCode.OK;
            }
        }
开发者ID:Roblinde,项目名称:GSA-Web-api,代码行数:40,代码来源:FeedClient.cs

示例10: SinglePhish

        private async void SinglePhish()
        {
            var form = (HtmlForm)lbForms.SelectedItem;
            var fields = form.Inputs;
            Phish phish = new Phish(fields);
            WebClient wc = new WebClient();

            Uri actionUrl;
            if (!Uri.TryCreate(_uri, form.ActionUrl, out actionUrl)) return;


            await Task.Run(() =>
                         {
                             try
                             {
                                 wc.UploadValuesAsync(actionUrl, phish.NVC);
                             }
                             catch
                             {
                             }
                         });
        }
开发者ID:HWiese1980,项目名称:RottenPhish,代码行数:22,代码来源:MainWindow.xaml.cs

示例11: DoUploadImage

 public static void DoUploadImage(Image img, string filename, FormMain evntfrm)
 {
     var UploaderClient = new WebClient();
     UploaderClient.Proxy = null; // fix bug http://bytes.com/topic/net/answers/792637-webclient-freezes-ten-seconds-first-connect
     ImageConverter converter = new ImageConverter();
     UploaderClient.UploadProgressChanged += new UploadProgressChangedEventHandler(evntfrm.UploaderClient_UploadProgressChanged);
     UploaderClient.UploadValuesCompleted += new UploadValuesCompletedEventHandler(evntfrm.UploaderClient_UploadValuesCompleted);
     String imagedata;
     using (var stream = new MemoryStream())
     {
         if (Settings.Instance.UploadImageFormat == Settings.Format.Png)
         {
             img.Save(stream, ImageFormat.Png);
         }
         else
         {
             var encparams = new EncoderParameters(1);
             encparams.Param[0] = new EncoderParameter(Encoder.Quality, Settings.Instance.UploadImageQuality);
             img.Save(stream, ImageCodecInfo.GetImageDecoders().FirstOrDefault(fmt => fmt.FormatID == ImageFormat.Jpeg.Guid), encparams);
         }
         imagedata = Convert.ToBase64String(stream.ToArray());
     }
     var values = new NameValueCollection
         {
             { "key", Settings.Instance.ImgurApiKey },
             { "name", filename + "." + Settings.Instance.UploadImageFormat },
             { "image", imagedata }
         };
     string s = "Starting " + filename + " upload in format: " + Settings.Instance.UploadImageFormat + ", " + Utility.FormatBytes(imagedata.Length) + " - " + img.Width + "x" + img.Height;
     int i;
     if (evntfrm.listBoxImages.Items[0].ToString().StartsWith("Up"))
         i = 0;
     else
         i = evntfrm.listBoxImages.Items.Add(s);
     evntfrm.Log("(" + i + ") " + s);
     UploaderClient.UploadValuesAsync(imguri, "POST", values, i);
     UploadingClients.Add(i, UploaderClient);
 }
开发者ID:krich38,项目名称:Screenshotter,代码行数:38,代码来源:Utility.cs

示例12: sendPushNotification

        public static void sendPushNotification(int providerIndex, string key, string title, string message)
        {
            WebClient client = new WebClient();
            NameValueCollection data = new NameValueCollection();
            client.Proxy = null;

            Uri api = null;
            NameValueCollection parameters = null;

            if (providerIndex == 1)
            {
                parameters = new NameValueCollection {
                    { "token", "X52StO16VHy9Jho2mac2G0RNNJD6qP" },
                    { "user", key },
                    { "title", title },
                    { "message", message }
                };

                api = new Uri("https://api.pushover.net/1/messages.json");
            }
            else if (providerIndex == 2 || providerIndex == 3)
            {
                parameters = new NameValueCollection {
                    { "apikey", key },
                    { "application", "Dungeon Teller" },
                    { "event", title },
                    { "description", message }
                };

                if (providerIndex == 2)
                    api = new Uri("https://www.notifymyandroid.com/publicapi/notify");
                if (providerIndex == 3)
                    api = new Uri("https://api.prowlapp.com/publicapi/add");
            }

            client.UploadValuesAsync(api, "POST", parameters);
        }
开发者ID:siriuzwhite,项目名称:Dungeon-Teller,代码行数:37,代码来源:Notification.cs

示例13: Send

        public string Send(int timeoutSec = 10)
        {
            var wc = new WebClient();
            wc.UploadValuesCompleted += wc_UploadValuesCompleted;

            wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
            wc.Headers.Add("Origin", "http://elpis.adamhaile.net");

            if (PRequest.Proxy != null)
                wc.Proxy = PRequest.Proxy;

            wc.UploadValuesAsync(new Uri(_url), "POST", _params);

            DateTime start = DateTime.Now;
            while (!_uploadComplete && ((DateTime.Now - start).TotalMilliseconds < (timeoutSec * 1000)))
                Thread.Sleep(25);

            if (_uploadComplete)
                return _uploadResult;

            wc.CancelAsync();

            throw new Exception("Timeout waiting for POST to " + _url);
        }
开发者ID:reider-roque,项目名称:Elpis,代码行数:24,代码来源:PostSubmitter.cs

示例14: ExecuteAsync

        public void ExecuteAsync(Template template)
        {
            AsyncManager.OutstandingOperations.Increment();
            var client = new WebClient { Encoding = Encoding.UTF8 };
            client.UploadValuesCompleted += (s, e) =>
            {
                if (e.Error == null)
                {
                    template.Response = Encoding.UTF8.GetString(e.Result);
                }
                else
                {
                    var exception = (WebException)e.Error;
                    var responseStream = exception.Response.GetResponseStream();
                    if (responseStream != null)
                        template.Response = new StreamReader(responseStream, Encoding.UTF8).ReadToEnd();
                }
                AsyncManager.Parameters["template"] = template;

                AsyncManager.OutstandingOperations.Decrement();
            };

            // SandboxにTemplateをPOSTしてビルド&実行!
            // ※なのでTemplate内でIsPostを見ると常にtrue...
            var uri = new Uri(ConfigurationManager.AppSettings["SandboxUri"]);
            var values = new NameValueCollection();
            var extensions = new Dictionary<string, string>
                                 {
                                     {"cshtml", "csdoit"},
                                     {"vbhtml", "vbdoit"}
                                 };
            var pageName = "default." + extensions[template.Language ?? "cshtml"];
            values["Razor"] = template.Razor;
            values["PageName"] = pageName;
            client.UploadValuesAsync(uri, "POST", values);
        }
开发者ID:takepara,项目名称:RazorDoIt,代码行数:36,代码来源:HomeController.cs

示例15: PostToServer

        private void PostToServer( Session oSession )
        {
            string oauth = OAuth;
            string url = oSession.fullUrl;
            string request = oSession.GetRequestBodyAsString();
            string response = oSession.GetResponseBodyAsString();

            request = RequestRegex.Replace( request, "" );

            try {

                //*
                using ( System.Net.WebClient wc = new System.Net.WebClient() ) {
                    wc.Headers["User-Agent"] = "ElectronicObserver/v" + SoftwareInformation.VersionEnglish;

                    if ( Proxy != null ) {
                        wc.Proxy = Proxy;
                    }

                    System.Collections.Specialized.NameValueCollection post = new System.Collections.Specialized.NameValueCollection();
                    post.Add( "token", oauth );
                    // agent key for 'ElectronicObserver'
                    // https://github.com/about518/kanColleDbPost/issues/3#issuecomment-105534030
                    post.Add( "agent", "L57Mi4hJeCYinbbBSH5K" );
                    post.Add( "url", url );
                    post.Add( "requestbody", request );
                    post.Add( "responsebody", response );

                    wc.UploadValuesCompleted += ( sender, e ) => {
                        if ( e.Error != null ) {

                            // 結構頻繁に出るのでレポートは残さない方針で 申し訳ないです
                            //Utility.ErrorReporter.SendErrorReport( e.Error, string.Format( "艦これ統計データベースへの {0} の送信に失敗しました。", url.Substring( url.IndexOf( "/api" ) + 1 ) ) );

                            Utility.Logger.Add( 1, string.Format( "艦これ統計データベースへの {0} の送信に失敗しました。{1}", url.Substring( url.IndexOf( "/api" ) + 1 ), e.Error.Message ) );

                        } else {
                            Utility.Logger.Add( 1, string.Format( "艦これ統計データベースへ {0} を送信しました。", url.Substring( url.IndexOf( "/api" ) + 1 ) ) );
                        }
                    };

                    wc.UploadValuesAsync( new Uri( "http://api.kancolle-db.net/2/" ), post );
                }
                //*/

            } catch ( Exception ex ) {

                Utility.ErrorReporter.SendErrorReport( ex, "艦これ統計データベースへの送信中にエラーが発生しました。" );
            }
        }
开发者ID:n-taketi,项目名称:nanoKamoDechiPoi,代码行数:50,代码来源:APIKancolleDB.cs


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