隐藏

在C#中HttpClient.PostAsync方法代码示例

发布:2023/9/15 20:17:33作者:管理员 来源:本站 浏览次数:692



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


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

示例1: apiPOST


       public async Task<bool> apiPOST(string access_token, string response, string href)

       {

           

           mlibrary = new methodLibrary();

           HttpClient httpClient = new HttpClient();

           try

           {

               httpClient.DefaultRequestHeaders.Authorization = new HttpCredentialsHeaderValue("Bearer", access_token);

               httpClient.DefaultRequestHeaders.Accept.Add(new HttpMediaTypeWithQualityHeaderValue("application/json"));


               var httpResponseMessage = await httpClient.PostAsync(new Uri(href), new HttpStringContent(response));

               string resp = await httpResponseMessage.Content.ReadAsStringAsync();

               await mlibrary.writeFile("POSTresponse", resp);

               Debug.WriteLine(resp);

               ApplicationData.Current.LocalSettings.Values["POSTCallMade"] = true;

           }

           catch(Exception ex)

           {

               Debug.WriteLine("Caught exception : " + ex);

                             

               return false;

           }

           

           return true;

       }


开发者ID:agangal,项目名称:TeamSnapV3,代码行数:25,代码来源:Library_APICall.cs


示例2: TelemetryIngest


       public async Task<bool> TelemetryIngest(Telemetry telemetry)

       {


           string serviceBusNamespace = "iotmc-ns";

           string serviceBusUri = string.Format("{0}.servicebus.windows.net", serviceBusNamespace);

           string eventHubName = "IoTMC";

           string eventHubSASKeyName = "Device01";

           string eventHubSASKey = "<< Your SAS Key here >>";


           using (HttpClient httpClient = new HttpClient())

           {

               httpClient.BaseAddress = new Uri(String.Format("https://{0}", serviceBusUri));

               httpClient.DefaultRequestHeaders.Accept.Clear();


               string sBToken = CreateServiceBusSASToken(eventHubSASKeyName, eventHubSASKey, serviceBusUri);

               httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("SharedAccessSignature", sBToken);

               HttpContent httpContent = new StringContent(JsonConvert.SerializeObject(telemetry), Encoding.UTF8);

               httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");

             

               string ingestPath = String.Format("/{0}/publishers/device01/messages", eventHubName);

               var response = await httpClient.PostAsync(ingestPath, httpContent);

               if (response.IsSuccessStatusCode)

               {

                   return true;

               }


               return false;

           }

       }


开发者ID:HydAu,项目名称:IoTMasterClass,代码行数:29,代码来源:EventHubIngest.cs


示例3: HttpPost


       private async Task<string> HttpPost(string relativeUri, string json)

       {

           var cts = new CancellationTokenSource();

           cts.CancelAfter(5000);


           try

           {

               HttpClient client = new HttpClient();


               Uri uri = new Uri($"http://{Ip}:{Port}/api/{relativeUri}");

               HttpStringContent httpContent = new HttpStringContent(json);

               HttpResponseMessage response = await client.PostAsync(uri, httpContent).AsTask(cts.Token);


               if (!response.IsSuccessStatusCode)

               {

                   return string.Empty;

               }


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


               System.Diagnostics.Debug.WriteLine(jsonResponse);


               return jsonResponse;

           }

           catch (Exception)

           {

               return string.Empty;

           }

       }


开发者ID:bartreedijk,项目名称:TI-2.2-HueAppp,代码行数:29,代码来源:HueAPIConnector.cs


示例4: PostAsync


private static async Task<string> PostAsync(string url, string content)

{

   var client = new HttpClient();

   var response = await client.PostAsync(new Uri(url), new HttpStringContent(content));

   var result = await response.Content.ReadAsStringAsync();

   return result;

}


开发者ID:mrange,项目名称:funbasic,代码行数:7,代码来源:Web.cs


示例5: PostChatMessage


       public static async Task<Chat> PostChatMessage(int chatId, string message) {

           var chat = new Chat();


           //var authenticatedProfile = await Common.StorageService.RetrieveObjectAsync<Profile>("Profile");


           using (var httpClient = new HttpClient()) {

               var apiKey = Common.StorageService.LoadSetting("ApiKey");

               var apiUrl = Common.StorageService.LoadSetting("ApiUrl");

               var profileToken = Common.StorageService.LoadSetting("ProfileToken");


               httpClient.DefaultRequestHeaders.Add("Accept-Encoding", "gzip");

               httpClient.DefaultRequestHeaders.Add("token", apiKey);

               httpClient.DefaultRequestHeaders.Add("api-version", "2");

               httpClient.DefaultRequestHeaders.Add("profileToken", profileToken);


               var criteria = new NewChatMessageCriteria {

                   ChatId = chatId,

                   Message = message

               };


               var uri = new Uri(apiUrl + "/api/chat/message");

               var queryString = new HttpStringContent(JsonConvert.SerializeObject(criteria), Windows.Storage.Streams.UnicodeEncoding.Utf8, "application/json");


               HttpResponseMessage response = await httpClient.PostAsync(uri, queryString);

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

               json = json.Replace("<br>", Environment.NewLine);

               chat = JsonConvert.DeserializeObject<Chat>(json);

           }


           return chat;

       }


开发者ID:wvannigtevegt,项目名称:S2M_UWP,代码行数:31,代码来源:ChatMessage.cs


示例6: PostAsync


       public async Task<JsonValue> PostAsync(string relativeUri)

       {

           HttpStringContent content = new HttpStringContent(message.Stringify(), UnicodeEncoding.Utf8, "application/json");


           HttpClient httpClient = new HttpClient();

           HttpResponseMessage httpResponse = null;

           try

           {

               httpResponse = await httpClient.PostAsync(new Uri(serverBaseUri, relativeUri), content);

           }

           catch (Exception ex)

           {

               switch (ex.HResult)

               {

                   case E_WINHTTP_TIMEOUT:

                   // The connection to the server timed out.

                   case E_WINHTTP_NAME_NOT_RESOLVED:

                   case E_WINHTTP_CANNOT_CONNECT:

                   case E_WINHTTP_CONNECTION_ERROR:

                   // Unable to connect to the server. Check that you have Internet access.

                   default:

                       // "Unexpected error connecting to server: ex.Message

                       return null;

               }

           }


           // We assume that if the server responds at all, it responds with valid JSON.

           return JsonValue.Parse(await httpResponse.Content.ReadAsStringAsync());

       }


开发者ID:COMIsLove,项目名称:Windows-universal-samples,代码行数:29,代码来源:Util.cs


示例7: Authorize


       private async Task Authorize(string code)

       {

           Uri uri = new Uri("https://api.weibo.com/oauth2/access_token");


           List<KeyValuePair<string, string>> pairs = new List<KeyValuePair<string, string>>();


           pairs.Add(new KeyValuePair<string, string>("client_id", appInfo.Key));

           pairs.Add(new KeyValuePair<string, string>("client_secret", appInfo.Secret));

           pairs.Add(new KeyValuePair<string, string>("grant_type", "authorization_code"));

           pairs.Add(new KeyValuePair<string, string>("code", code));

           pairs.Add(new KeyValuePair<string, string>("redirect_uri", appInfo.RedirectUri));


           HttpFormUrlEncodedContent content = new HttpFormUrlEncodedContent(pairs);


           using (HttpClient client = new HttpClient())

           {

               DateTime time = DateTime.Now;


               HttpResponseMessage response;

               try

               {

                   response = await client.PostAsync(uri, content);

               }

               catch (Exception ex)

               {

                   throw new Exception("network error", ex);

               }

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


               JObject accessToken = JsonConvert.DeserializeObject<JObject>(json);

               UserInfo.Token = accessToken["access_token"].ToString();

               UserInfo.ExpiresAt = Untils.ToTimestamp(time) + (long)accessToken["expires_in"];

               UserInfo.Uid = accessToken["uid"].ToString();

           }

       }


开发者ID:tianzhaodong,项目名称:uwp_AiJianShu,代码行数:35,代码来源:WeiboClient.cs


示例8: PostFormNoParse


       private static async Task<string> PostFormNoParse(string url, Dictionary<string, string> args) {

           var client = new HttpClient();


           var response = await client.PostAsync(new Uri(url), new HttpFormUrlEncodedContent(args));

           var responseString = await response.Content.ReadAsStringAsync();

           return responseString;

       }


开发者ID:LoveMetal-StrangeGames,项目名称:4Chat,代码行数:7,代码来源:API.cs


示例9: SetCarUnit


       //public List<CartUnit> Units { get; set; }

       //public List<CartOption> Options { get; set; }


       public static async Task<Cart> SetCarUnit(CancellationToken token, string cartKey, int searchDateId, int unitId, int currencyId, double pricePerItem, int taxId, long crc) {

           var cart = new Cart();


           using (var httpClient = new HttpClient()) {

               var apiKey = Common.StorageService.LoadSetting("ApiKey");

               var apiUrl = Common.StorageService.LoadSetting("ApiUrl");

               var profileToken = Common.StorageService.LoadSetting("ProfileToken");


               httpClient.DefaultRequestHeaders.Add("Accept-Encoding", "gzip");

               httpClient.DefaultRequestHeaders.Add("token", apiKey);

               httpClient.DefaultRequestHeaders.Add("api-version", "2");

               httpClient.DefaultRequestHeaders.Add("profileToken", profileToken);


               var criteria = new CartUnitCriteria() {

                   CartKey = cartKey,

                   SearchDateId = searchDateId,

                   UnitId = unitId,

                   CurrencyId = currencyId,

                   PricePerItem = pricePerItem,

                   TaxId = taxId,

                   Crc = crc

               };


               var url = apiUrl + "/api/cart/unit/";

               var queryString = new HttpStringContent(JsonConvert.SerializeObject(criteria), Windows.Storage.Streams.UnicodeEncoding.Utf8, "application/json");


               using (var httpResponse = await httpClient.PostAsync(new Uri(url), queryString).AsTask(token)) {

                   string json = await httpResponse.Content.ReadAsStringAsync().AsTask(token);

                   json = json.Replace("<br>", Environment.NewLine);

                   cart = JsonConvert.DeserializeObject<Cart>(json);

               }

           }


           return cart;

       }


开发者ID:wvannigtevegt,项目名称:S2M_UWP,代码行数:38,代码来源:Cart.cs


示例10: ExecuteAsync


public async Task<string> ExecuteAsync()

{

    if (OAuthSettings.AccessToken != null)

    {

        return OAuthSettings.AccessToken;

    }

    else if (OAuthSettings.RefreshToken == null)

    {

        return null;

    }

    using (var client = new HttpClient())

    {

        var content = new HttpFormUrlEncodedContent(new Dictionary<string, string>{

                        {"grant_type","refresh_token"},

                        {"refresh_token", OAuthSettings.RefreshToken},

                        {"client_id", OAuthSettings.ClientId},

                        {"client_secret", OAuthSettings.ClientSecret}

                    });

        var response = await client.PostAsync(new Uri(OAuthSettings.TokenEndpoint), content);

        response.EnsureSuccessStatusCode();

        var contentString = await response.Content.ReadAsStringAsync();

        var accessTokenInfo = await JsonConvert.DeserializeObjectAsync<OAuthTokenInfo>(contentString);

        OAuthSettings.AccessToken = accessTokenInfo.AccessToken;

        OAuthSettings.RefreshToken = accessTokenInfo.RefreshToken;

        return OAuthSettings.AccessToken;

    }

}


开发者ID:jcorioland,项目名称:techdays-paris-2014-mvc-webapi,代码行数:27,代码来源:LoginPassivelyQuery.cs


示例11: Initialize


       public async Task<bool> Initialize()

       {

           _client = new HttpClient();


           // Define the data needed to request an authorization token.

           var service = "https://datamarket.accesscontrol.windows.net/v2/OAuth2-13";

           var scope = "http://music.xboxlive.com";

           var grantType = "client_credentials";


           // Create the request data.

           var requestData = new Dictionary<string, string>();

           requestData["client_id"] = CLIENT_ID;

           requestData["client_secret"] = CLIENT_SECRET;

           requestData["scope"] = scope;

           requestData["grant_type"] = grantType;


           // Post the request and retrieve the response.

           string token = null;

           var response = await _client.PostAsync(new Uri(service), new HttpFormUrlEncodedContent(requestData));

           var responseString = await response.Content.ReadAsStringAsync();

           if (response.IsSuccessStatusCode)

           {

               token = Regex.Match(responseString, ".*\"access_token\":\"(.*?)\".*", RegexOptions.IgnoreCase).Groups[1].Value;

           }

           else

           {

               await new MessageDialog("Authentication failed. Please provide a valid client.").ShowAsync();

               App.Current.Exit();

           }

           

           Token = token;

           return (token != null) ? true : false;

       }


开发者ID:punker76,项目名称:composition,代码行数:33,代码来源:RemoteDataSource.cs


示例12: AcquireLicense


       /// <summary>

       /// Invoked to acquire the PlayReady license.

       /// </summary>

       /// <param name="licenseServerUri">License Server URI to retrieve the PlayReady license.</param>

       /// <param name="httpRequestContent">HttpContent including the Challenge transmitted to the PlayReady server.</param>

       public async virtual Task<IHttpContent> AcquireLicense(Uri licenseServerUri, IHttpContent httpRequestContent)

       {

           try

           {

               HttpClient httpClient = new HttpClient();

               httpClient.DefaultRequestHeaders.Add("msprdrm_server_redirect_compat", "false");

               httpClient.DefaultRequestHeaders.Add("msprdrm_server_exception_compat", "false");


               HttpResponseMessage response = await httpClient.PostAsync(licenseServerUri, httpRequestContent);

               response.EnsureSuccessStatusCode();

               

               if (response.StatusCode == HttpStatusCode.Ok)

               {

                   _lastErrorMessage = string.Empty;

                   return response.Content;

               }

               else

               {

                   _lastErrorMessage = "AcquireLicense - Http Response Status Code: " + response.StatusCode.ToString();

               }

           }

           catch (Exception exception)

           {

               _lastErrorMessage = exception.Message;

               return null;

           }

           return null;

       }


开发者ID:flecoqui,项目名称:Windows10,代码行数:33,代码来源:CommonLicenseRequest.cs


示例13: Post


       private async Task<String> Post(string path, string json)

       {

           var cts = new CancellationTokenSource();

           cts.CancelAfter(5000);


           try

           {

               HttpClient client = new HttpClient();

               HttpStringContent content = new HttpStringContent(json, Windows.Storage.Streams.UnicodeEncoding.Utf8, "application /json");


               Uri uriLampState = new Uri("http://127.0.0.1:8000/api/" + path);

               var response = await client.PostAsync(uriLampState, content).AsTask(cts.Token);


               if (!response.IsSuccessStatusCode)

               {

                   return string.Empty;

               }


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


               return jsonResponse;

           }

           catch (Exception ex)

           {

               System.Diagnostics.Debug.WriteLine(ex.Message);

               return string.Empty;

           }

       }


开发者ID:aareschluchtje,项目名称:HueLamps,代码行数:28,代码来源:Networkfixer.cs


示例14: PostStringAsync


       public async Task<string> PostStringAsync(string link, string param)

       {


           try

           {


               System.Diagnostics.Debug.WriteLine(param);


               Uri uri = new Uri(link);


               HttpClient httpClient = new HttpClient();



               HttpStringContent httpStringContent = new HttpStringContent(param, Windows.Storage.Streams.UnicodeEncoding.Utf8,"application/x-www-form-urlencoded"); //,Windows.Storage.Streams.UnicodeEncoding.Utf8

               

               HttpResponseMessage response = await httpClient.PostAsync(uri,


                                                      httpStringContent).AsTask(cts.Token);

               responseHeaders = response.Headers;

               System.Diagnostics.Debug.WriteLine(responseHeaders);


               string responseBody = await response.Content.ReadAsStringAsync().AsTask(cts.Token);

               return responseBody;

           }

           catch(Exception e)

           {

               return "Error:" + e.Message;

           }


       }


开发者ID:xulihang,项目名称:jnrain-wp,代码行数:30,代码来源:httputils.cs


示例15: DoLogin


       /// <summary>

       /// 约定成功登陆返回0,不成功返回错误代码,未知返回-1

       /// </summary>

       /// <returns></returns>

       public async Task<int> DoLogin()

       {

           var httpClient = new HttpClient();

           var requestUrl = "https://net.zju.edu.cn/cgi-bin/srun_portal";

           var formcontent = new HttpFormUrlEncodedContent(new[]

           {

               new KeyValuePair<string, string>("action","login"),

               new KeyValuePair<string, string>("username",_mAccount.Username),

               new KeyValuePair<string, string>("password",_mAccount.Password),

               new KeyValuePair<string, string>("ac_id","3"),

               new KeyValuePair<string, string>("type","1"),

               new KeyValuePair<string, string>("wbaredirect",@"http://www.qsc.zju.edu.cn/"),

               new KeyValuePair<string, string>("mac","undefined"),

               new KeyValuePair<string, string>("user_ip",""),

               new KeyValuePair<string, string>("is_ldap","1"),

               new KeyValuePair<string, string>("local_auth","1"),

           });

           var response = await httpClient.PostAsync(new Uri(requestUrl), formcontent);

           if (response.Content != null)

           {

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

               Debug.WriteLine(textMessage);

           }


           httpClient.Dispose();


           return -1;

       }