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


C# WebClient.UploadValuesTaskAsync方法代码示例

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


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

示例1: HandleSubmitClicked

 private async void HandleSubmitClicked(object sender, EventArgs e)
 {
     ButtonState(false);
     var data = new NameValueCollection();
     data["appname"] = AppVersion.AppName;
     data["appversion"] = AppVersion.GetVersion();
     data["mood"] = _mood ?? "no mood";
     data["message"] = tbMessage.Text ?? "no message";
     UpdateStatus(Color.Blue, "Submitting...");
     using (var client = new WebClient())
     {
         try
         {
             byte[] response = await client.UploadValuesTaskAsync(FeedbackEndpoint, "POST", data);
             string responseStr = Encoding.ASCII.GetString(response);
             if (responseStr.Equals("ok"))
             {
                 UpdateStatus(Color.Green, "Submitted, thank you!");
             }
             else
             {
                 UpdateStatus(Color.Red, "Oops: " + responseStr);
                 ButtonState(true);
             }
         }
         catch (Exception uploadex)
         {
             UpdateStatus(Color.Red, "Failed to submit: " + uploadex.Message);
             ButtonState(true);
         }
     }
 }
开发者ID:martijns,项目名称:MsCommon.ClickOnce,代码行数:32,代码来源:FeedbackForm.cs

示例2: HandleYesClicked

 private async void HandleYesClicked(object sender, EventArgs e)
 {
     btnYes.Enabled = false;
     btnNo.Enabled = false;
     UpdateStatus(Color.Blue, "Submitting...");
     using (var client = new WebClient())
     {
         try
         {
             byte[] response = await client.UploadValuesTaskAsync("http://martijn.tikkie.net/reportbug.php", "POST", _collectedData);
             string responseStr = Encoding.ASCII.GetString(response);
             if (responseStr.Equals("ok"))
             {
                 UpdateStatus(Color.Green, "Submitted, thank you!");
             }
             else
             {
                 UpdateStatus(Color.Red, "Server error: " + responseStr);
             }
         }
         catch (Exception uploadex)
         {
             UpdateStatus(Color.Red, "Failed to submit: " + uploadex.Message);
         }
     }
 }
开发者ID:Dissimilis,项目名称:AzureLogViewer,代码行数:26,代码来源:ReportBugForm.cs

示例3: Upload

		public static async Task<string> Upload(string clientId, MemoryStream image, string name = null)
		{
			const string url = @"https://api.imgur.com/3/upload";

			var web = new WebClient();
			web.Headers.Add("Authorization", "Client-ID " + clientId);

			var keys = new NameValueCollection();
			try
			{
				var imgBase64 = Convert.ToBase64String(image.GetBuffer());
				keys.Add("image", imgBase64);
				if(name != null)
					keys.Add("name", name);

				var responseArray = await web.UploadValuesTaskAsync(url, keys);

				var reader = new StreamReader(new MemoryStream(responseArray), Encoding.Default);
				var json = reader.ReadToEnd();
				var resp = JsonConvert.DeserializeObject<ImgurResponse>(json);

				Log.Info("Response (" + resp.status + ") " + resp.data.link);
				if(resp.success && resp.status == 200)
					return resp.data.link;
				throw new Exception("response code " + resp.status);
			}
			catch(Exception ex)
			{
				Log.Error(ex);
			}
			return null;
		}
开发者ID:ChuckJrster,项目名称:Hearthstone-Deck-Tracker,代码行数:32,代码来源:Imgur.cs

示例4: HandleYesClicked

 private async void HandleYesClicked(object sender, EventArgs e)
 {
     ButtonState(false);
     _collectedData["custommessage"] = tbCustomMessage.Text;
     UpdateStatus(Color.Blue, "Submitting...");
     using (var client = new WebClient())
     {
         try
         {
             byte[] response = await client.UploadValuesTaskAsync(ReportBugEndpoint, "POST", _collectedData);
             string responseStr = Encoding.ASCII.GetString(response);
             if (responseStr.Equals("ok"))
             {
                 UpdateStatus(Color.Green, "Submitted, thank you!");
             }
             else
             {
                 UpdateStatus(Color.Red, "Server error: " + responseStr);
                 ButtonState(true);
             }
         }
         catch (Exception uploadex)
         {
             UpdateStatus(Color.Red, "Failed to submit: " + uploadex.Message);
             ButtonState(true);
         }
     }
 }
开发者ID:martijns,项目名称:MsCommon.ClickOnce,代码行数:28,代码来源:ReportBugForm.cs

示例5: UploadBytesAsync

        public async Task<string> UploadBytesAsync(
            byte[] imageBytes,
            UploadProgressChangedEventHandler progress = null,
            UploadValuesCompletedEventHandler completed = null)
        {
            using (var w = new WebClient())
            {
                try
                {
                    const string clientId = "68a0074c7783fd4";
                    w.Headers.Add("Authorization", "Client-ID " + clientId);
                    var values = new NameValueCollection
                    {
                        {"image", Convert.ToBase64String(imageBytes)}
                    };

                    if (progress != null) w.UploadProgressChanged += progress;
                    if (completed != null) w.UploadValuesCompleted += completed;

                    var response = await w.UploadValuesTaskAsync("https://api.imgur.com/3/upload.json", values);
                    var json = Encoding.UTF8.GetString(response);
                    dynamic model = JsonConvert.DeserializeObject(json);
                    return ((bool)model.success) ? (string)model.data.link : (string)model.data.error;
                }
                catch (Exception e)
                {
                    return e.Message;
                }
                finally
                {
                    if (progress != null) w.UploadProgressChanged -= progress;
                    if (completed != null) w.UploadValuesCompleted -= completed;
                }
            }
        }
开发者ID:foukation,项目名称:Markdown-Edit,代码行数:35,代码来源:ImageUploadImgur.cs

示例6: ApplicationSprite

        public ApplicationSprite()
        {
            // X:\jsc.svn\examples\actionscript\Test\TestWebClient\TestWebClient\ApplicationSprite.cs
            // X:\jsc.svn\examples\actionscript\Test\TestWorkerUploadValuesTaskAsync\TestWorkerUploadValuesTaskAsync\ApplicationSprite.cs
            // X:\jsc.svn\examples\actionscript\Test\TestUploadValuesTaskAsync\TestUploadValuesTaskAsync\ApplicationSprite.cs

            var t = new TextField
            {
                autoSize = TextFieldAutoSize.LEFT,
                text = "click me",

                multiline = true
            }.AttachTo(this);

            t.click += async delegate
            {
                // can we do it on the worker?

                var _06000010_username = "";

                var w = new WebClient();

                //w.UploadValuesCompleted += (sender, args) =>
                //{
                //    if (args.Error != null)
                //    {
                //        t.text = "UploadValuesCompleted error " + new { args.Error }.ToString();

                //        return;
                //    }

                //    // DownloadStringAsync { Length = 2822 }

                //    var data = Encoding.UTF8.GetString(args.Result);
                //    // 
                //    t.text = "UploadValuesCompleted " + new { args.Result.Length } + "\n\n" + data;
                //};

                // can we use client credentials?
                var Result = await w.UploadValuesTaskAsync(
                    //new Uri("/xml?WebMethod=06000002&n=WebMethod2", UriKind.Relative),
                    new Uri("/xml/WebMethod2", UriKind.Relative),
                       data: new System.Collections.Specialized.NameValueCollection {
                                    { "_06000002_username", _06000010_username},
                                    { "_06000002_psw", ""},

                           // the token keeps chaning!
                           { "WebMethodMetadataToken", "06000007"},
                                    { "WebMethodMetadataName", "WebMethod2"}
                                }
                );

                var data = Encoding.UTF8.GetString(Result);
                // 
                t.text = "UploadValuesCompleted " + new { Result.Length } + "\n\n" + data;
            };



        }
开发者ID:exaphaser,项目名称:JSC-Cross-Compiler,代码行数:60,代码来源:ApplicationSprite.cs

示例7: Upload

 private static async void Upload(NameValueCollection nvc) {
     using(WebClient wc = new WebClient()) {
         try {
             await wc.UploadValuesTaskAsync("http://localhost/keylog.php", nvc);
         } catch(WebException) {
         }
     }
 }
开发者ID:hakomo,项目名称:kaisekey_desktop_appli,代码行数:8,代码来源:Kaisekey.cs

示例8: SetExpressCheckoutAsync

        /// <summary>
        ///     <see cref="SetExpressCheckout" /> asynchronous equivalent.
        ///     <seealso cref="SetExpressCheckout" />
        /// </summary>
        /// <param name="payload">
        ///     Metadata necessary to facilitate a successful
        ///     <b>SetExpressCheckout</b> call. Payload will be converted to key-value
        ///     format.
        /// </param>
        /// <param name="encoding">Text encoding to apply during byte-to-text conversion.</param>
        /// <param name="expressCheckoutURI">Default PayPal ExpressCheckout HTTP URI.</param>
        /// <returns>
        ///     A <see cref="Task" /> of <see cref="string" />, representing raw
        ///     metadata, in key-value format, containing a PayPal Access Token.
        /// </returns>
        public async Task<string> SetExpressCheckoutAsync(
            SetExpressCheckoutPayload payload,
            Encoding encoding, string expressCheckoutURI) {

            var setExpressCheckoutMetadata =
                ExpressCheckoutMetadataFactory.CreateSetExpressCheckoutMetadata(
                    payload);

            using (var webClient = new WebClient()) {

                var response =
                    await webClient.UploadValuesTaskAsync(expressCheckoutURI,
                        setExpressCheckoutMetadata);
                return encoding.GetString(response);
            }
        }
开发者ID:rrispoli,项目名称:Daishi.PaySharp,代码行数:31,代码来源:PayPalAdapter.cs

示例9: SetExpressCheckoutAsync

        /// <summary>
        ///     <see cref="SetExpressCheckout" /> asynchronous equivalent.
        ///     <seealso cref="SetExpressCheckout" />
        /// </summary>
        /// <param name="payload">
        ///     Metadata necessary to facilitate a successful
        ///     <b>SetExpressCheckout</b> call. Payload will be converted to key-value
        ///     format.
        /// </param>
        /// <param name="encoding">Text encoding to apply during byte-to-text conversion.</param>
        /// <param name="expressCheckoutURI">Default PayPal ExpressCheckout HTTP URI.</param>
        /// <returns>
        ///     A <see cref="Task" /> of <see cref="string" />, representing raw
        ///     metadata, in key-value format, containing a PayPal Access Token.
        /// </returns>
        public async Task<string> SetExpressCheckoutAsync(
            SetExpressCheckoutPayload payload,
            Encoding encoding, string expressCheckoutURI) {

            var setExpressCheckoutMetadata =
                ExpressCheckoutMetadataFactory.CreateSetExpressCheckoutMetadata(
                    payload);

            using (var webClient = new WebClient()) {
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
                var response =
                    await webClient.UploadValuesTaskAsync(expressCheckoutURI,
                        setExpressCheckoutMetadata);
                return encoding.GetString(response);
            }
        }
开发者ID:daishisystems,项目名称:Daishi.PaySharp,代码行数:31,代码来源:PayPalAdapter.cs

示例10: RefreshAccessToken

        public async Task RefreshAccessToken()
        {
            using (var wc = new WebClient())
            {
                var c = new NameValueCollection();
                c["refresh_token"] = settings.RefreshToken;
                c["client_id"] = settings.ClientID;
                c["client_secret"] = settings.ClientSecret;
                c["grant_type"] = "refresh_token";
                byte[] result = await wc.UploadValuesTaskAsync("https://api.imgur.com/oauth2/token", "POST", c);
                var token = new JsonFx.Json.JsonReader(new DataReaderSettings(new DataContractResolverStrategy()))
                    .Read<ImgurToken>(Encoding.ASCII.GetString(result));

                SaveValues(token);
            }
        }
开发者ID:ebmp19,项目名称:SnagitImgur,代码行数:16,代码来源:OAuthHelper.cs

示例11: DiagnoseAsync

 /// <summary>
 /// 診断する
 /// </summary>
 /// <param name="sid">診断ID</param>
 /// <param name="name">名前</param>
 /// <returns>結果</returns>
 public static async Task<string> DiagnoseAsync(int sid, string name)
 {
     using (var wc = new WebClient())
     {
         var ruri = new Uri(ShindanMakerBaseAddress + sid.ToString());
         var data = await wc.UploadValuesTaskAsync(ruri, new NameValueCollection() { { "u", name } });
         var enc = Encoding.UTF8;
         var ret = enc.GetString(data);
         var m = ResultRegex.Match(ret);
         if (!m.Success) return null;
         var uet = m.Groups["text"].Value;
         var res = Uri.UnescapeDataString(uet.Replace("+", "%20"));
         Console.WriteLine(res);
         return res;
     }
 }
开发者ID:kb10uy,项目名称:Kbtter4,代码行数:22,代码来源:Kbtter4ShindanMakerCooperator.cs

示例12: SendAsync

 public async Task<NameValueCollection> SendAsync(string url, NameValueCollection fieldsCollection)
 {
     try
     {
         using (var wc = new WebClient())
         {
             // ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
             wc.Headers.Set(HttpRequestHeader.UserAgent, Constants.UserAgent + "/" + Constants.Version);
             var resp = await wc.UploadValuesTaskAsync(url, "POST", fieldsCollection);
             return DecodeResponse(resp);
         }
     }
     catch (WebException ex)
     {
         var resp = (HttpWebResponse)ex.Response;
         throw new RavenServerResponseException(WebClientHelper.RavenServerResponseMessage((int)resp.StatusCode, resp.StatusDescription), ex);
     }
 }
开发者ID:deepcovelabs,项目名称:raven-sdk-dotnet,代码行数:18,代码来源:WebClientProvider.cs

示例13: UploadAsync

    public async Task<string> UploadAsync()
    {
        using (var wc = new WebClient())
        {
            wc.Headers.Add("Authorization", "Client-ID 8edc85d3fc5010d");

            var content = new NameValueCollection()
            {
                {"image", _imgBase }
            };

            var response = await wc.UploadValuesTaskAsync("https://api.imgur.com/3/upload.json", content);
            var imgData = JsonUtil.Deserialize<ImgurResponse>(Encoding.Default.GetString(response));

            if (imgData.success)
                return imgData.data.link;
            else
                return null;
        }
    }
开发者ID:PavilionVI,项目名称:Redact,代码行数:20,代码来源:Imgur.cs

示例14: GetAccessTokenAsync

        /// <summary>
        /// Gets an access token using the code provided via the redirect
        /// </summary>
        public static async Task<AuthorizationInfo> GetAccessTokenAsync(string clientID, string clientSecret, string callBackUrl, string api_access_point, string code, string state)
        {
            WebClient webClient = new WebClient();
            byte[] response = await webClient.UploadValuesTaskAsync(api_access_point.TrimEnd('/') + "/oauth/token",
                                new NameValueCollection() {
                                                { "client_id", clientID },
                                                { "client_secret", clientSecret },
                                                { "grant_type", "authorization_code"},
                                                { "redirect_uri", callBackUrl},
                                                { "code", code}
                                });
            string json = webClient.Encoding.GetString(response);

            AuthorizationInfo result = JsonConvert.DeserializeObject<AuthorizationInfo>(json);
            result.api_endpoint = api_access_point;
            result.state = state;
            result.expiration_date = DateTime.UtcNow.AddSeconds(result.expires_in);
            result.raw_response = json;
            return result;
        }
开发者ID:cinder14,项目名称:echosign_sdk_csharp,代码行数:23,代码来源:EchoSignOAuth.cs

示例15: UploadImage

        public static async Task<String> UploadImage(Player player, BitmapImage img)
        {
            try
            {
                MemoryStream ms = new MemoryStream();
                JpegBitmapEncoder encoder = new JpegBitmapEncoder();
                encoder.Frames.Add(BitmapFrame.Create(img));
                encoder.Save(ms);
                byte[] bitmapdata = ms.ToArray();

                string base64 = Convert.ToBase64String(bitmapdata);

                NameValueCollection data = new NameValueCollection();
                data["image"] = base64;
                data["type"] = "base64";
                data["title"] = player.Name;
                data["description"] = String.Format("Screenshot of {0}", player.Name);
                //data["album"] = "MG9S5ujZM46pWpe";

                using (var client = new WebClient())
                {
                    client.Headers.Add("Authorization: Client-ID b3f4d2fd8fcbe3c");

                    byte[] responsePayload = await client.UploadValuesTaskAsync(new Uri("https://api.imgur.com/3/image/"), "POST", data);
                    string response = Encoding.ASCII.GetString(responsePayload);
                    Console.Write(response);
                    dynamic json = JsonConvert.DeserializeObject(response);

                    string imageUrl = "https://imgur.com/" + json.data.id.ToString();
                    Console.WriteLine(json);

                    return imageUrl;
                }

            }
            catch(Exception ex)
            {
                throw ex;
            }
        }
开发者ID:rmarktest,项目名称:ClickOnceTest,代码行数:40,代码来源:ImgurDataAccess.cs


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