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


C# HttpClient.PostAsync方法代码示例

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


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

示例1: sendPost

        public void sendPost()
        {
            // Définition des variables qui seront envoyés
            HttpContent stringContent1 = new StringContent(param1String); // Le contenu du paramètre P1
            HttpContent stringContent2 = new StringContent(param2String); // Le contenu du paramètre P2
            HttpContent fileStreamContent = new StreamContent(paramFileStream);
            //HttpContent bytesContent = new ByteArrayContent(paramFileBytes);

            using (var client = new HttpClient())
            using (var formData = new MultipartFormDataContent())
            {
                formData.Add(stringContent1, "P1"); // Le paramètre P1 aura la valeur contenue dans param1String
                formData.Add(stringContent2, "P2"); // Le parmaètre P2 aura la valeur contenue dans param2String
                formData.Add(fileStreamContent, "FICHIER", "RETURN.xml");
                //  formData.Add(bytesContent, "file2", "file2");
                try
                {
                    var response = client.PostAsync(actionUrl, formData).Result;
                    MessageBox.Show(response.ToString());
                    if (!response.IsSuccessStatusCode)
                    {
                        MessageBox.Show("Erreur de réponse");
                    }
                }
                catch (Exception Error)
                {
                    MessageBox.Show(Error.Message);
                }
                finally
                {
                    client.CancelPendingRequests();
                }
            }
        }
开发者ID:microint,项目名称:WindowsFormsPostRequest,代码行数:34,代码来源:Form1.cs

示例2: MashapeFacebookLogin

        public async Task MashapeFacebookLogin()
        {
            //NOTE: Check App.xaml.cs for the variables that you need to fill in

            var targeturi = "https://ismaelc-facebooktest.p.mashape.com/oauth_url";

            var client = new System.Net.Http.HttpClient();

            HttpContent content = new FormUrlEncodedContent(new[]
            {
                new KeyValuePair<string, string>("consumerKey", App.ConsumerKey),
                new KeyValuePair<string, string>("consumerSecret", App.ConsumerSecret),
                new KeyValuePair<string, string>("callbackUrl", App.CallbackUrl)
            });

            content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
            content.Headers.Add("X-Mashape-Authorization", App.MashapeHeader);

            progressRing.IsActive = true;
            btnLogin.IsEnabled = false;
            var response = await client.PostAsync(targeturi, content);
            progressRing.IsActive = false;
            btnLogin.IsEnabled = true;

            if (response.IsSuccessStatusCode)
            {
                string respContent = await response.Content.ReadAsStringAsync();
                string loginUrl = await Task.Run(() => JsonObject.Parse(respContent).GetNamedString("url"));

                WebAuthenticationResult WebAuthenticationResult = await WebAuthenticationBroker.AuthenticateAsync(
                                                        WebAuthenticationOptions.None,
                                                        new Uri(loginUrl),
                                                        new Uri(App.CallbackUrl));

                
                if (WebAuthenticationResult.ResponseStatus == WebAuthenticationStatus.Success)
                {
                    btnLogin.Visibility = Windows.UI.Xaml.Visibility.Collapsed;

                    var callBackUrl = WebAuthenticationResult.ResponseData.ToString();
                    //Where's ParseQueryString when you need it...
                    App.AccessToken = GetParameter(callBackUrl, "accessToken");
                    //App.AccessSecret = GetParameter(callBackUrl, "accessSecret");

                }
                else if (WebAuthenticationResult.ResponseStatus == WebAuthenticationStatus.ErrorHttp)
                {
                    throw new InvalidOperationException("HTTP Error returned by AuthenticateAsync() : " + WebAuthenticationResult.ResponseErrorDetail.ToString());
                }
                else
                {
                    // The user canceled the authentication
                }
            }
            else
            {
                //The POST failed, so update the UI accordingly
                //txtBlockResult.Text = "Error";
            }
        }
开发者ID:ismaelc,项目名称:MashapeFBSentimentExample,代码行数:60,代码来源:MainPage.xaml.cs

示例3: SetupAutoCADIOContainer

        /// <summary>
        /// Does setup of AutoCAD IO. 
        /// This method will need to be invoked once before any other methods of this
        /// utility class can be invoked.
        /// </summary>
        /// <param name="autocadioclientid">AutoCAD IO Client ID - can be obtained from developer.autodesk.com</param>
        /// <param name="autocadioclientsecret">AutoCAD IO Client Secret - can be obtained from developer.autodesk.com</param>
        public static void SetupAutoCADIOContainer(String autocadioclientid, String autocadioclientsecret)
        {
            try
            {
                String clientId = autocadioclientid;
                String clientSecret = autocadioclientsecret;

                Uri uri = new Uri("https://developer.api.autodesk.com/autocad.io/us-east/v2/");
                container = new AIO.Operations.Container(uri);
                container.Format.UseJson();

                using (var client = new HttpClient())
                {
                    var values = new List<KeyValuePair<string, string>>();
                    values.Add(new KeyValuePair<string, string>("client_id", clientId));
                    values.Add(new KeyValuePair<string, string>("client_secret", clientSecret));
                    values.Add(new KeyValuePair<string, string>("grant_type", "client_credentials"));
                    var requestContent = new FormUrlEncodedContent(values);
                    var response = client.PostAsync("https://developer.api.autodesk.com/authentication/v1/authenticate", requestContent).Result;
                    var responseContent = response.Content.ReadAsStringAsync().Result;
                    var resValues = JsonConvert.DeserializeObject<Dictionary<string, string>>(responseContent);
                    _accessToken = resValues["token_type"] + " " + resValues["access_token"];
                    if (!string.IsNullOrEmpty(_accessToken))
                    {
                        container.SendingRequest2 += (sender, e) => e.RequestMessage.SetHeader("Authorization", _accessToken);
                    }
                }
            }
            catch (System.Exception ex)
            {
                Console.WriteLine(String.Format("Error while connecting to https://developer.api.autodesk.com/autocad.io/v2/", ex.Message));
                container = null;
                throw;
            }
        }
开发者ID:CADblokeCADforks,项目名称:library-dotnet-autocad.io,代码行数:42,代码来源:AutoCADIOUtilities.cs

示例4: AlbumsControllerTest

        private static async Task AlbumsControllerTest(HttpClient client)
        {
            // create album
            await client.PostAsync("Albums/Create",
                new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>("title", "album 009") }));
            await client.PostAsync("Albums/Create",
                new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>("title", "album 010") }));

            // get all albums
            Console.WriteLine(await client.GetStringAsync("Albums/All"));

            // update album
            await client.PutAsync("Albums/Update",
                new FormUrlEncodedContent(new[]
                {
                    new KeyValuePair<string, string>("id", "2"),
                    new KeyValuePair<string, string>("year", "2014"),
                    new KeyValuePair<string, string>("producer", "gosho ot pochivka")
                }));

            // delete album 
            await client.DeleteAsync("Albums/Delete/1");

            // add song to album
            await client.PutAsync("Albums/AddSong?albumId=2&songId=2", null);

            // add artist to album
            await client.PutAsync("Albums/AddArtist?albumId=2&artistId=2", null);
        }
开发者ID:reminchev,项目名称:SoftUni-Projects,代码行数:29,代码来源:ConsoleClient.cs

示例5: RunAsync

        private async Task RunAsync(string url)
        {
            HttpClientHandler handler = new HttpClientHandler();
            handler.CookieContainer = new CookieContainer();

            using (var httpClient = new HttpClient(handler))
            {
                var loginUrl = url + "Account/Login";

                _traceWriter.WriteLine("Sending http GET to {0}", loginUrl);
                var response = await httpClient.GetAsync(loginUrl);
                var content = await response.Content.ReadAsStringAsync();
                var requestVerificationToken = ParseRequestVerificationToken(content);
                content = requestVerificationToken + "&UserName=user&Password=password&RememberMe=false";

                _traceWriter.WriteLine("Sending http POST to {0}", loginUrl);
                response = await httpClient.PostAsync(loginUrl, new StringContent(content, Encoding.UTF8, "application/x-www-form-urlencoded"));
                content = await response.Content.ReadAsStringAsync();
                requestVerificationToken = ParseRequestVerificationToken(content);

                await RunPersistentConnection(url, httpClient, handler.CookieContainer, requestVerificationToken);
                await RunHub(url, httpClient, handler.CookieContainer, requestVerificationToken);
                
                _traceWriter.WriteLine();
                _traceWriter.WriteLine("Sending http POST to {0}", url + "Account/LogOff");
                response = await httpClient.PostAsync(url + "Account/LogOff", CreateContent(requestVerificationToken));
                
                _traceWriter.WriteLine("Sending http POST to {0}", url + "Account/Logout");
                response = await httpClient.PostAsync(url + "Account/Logout", CreateContent(requestVerificationToken));
            }
        }
开发者ID:nedalco,项目名称:CookieAuthenticationSample,代码行数:31,代码来源:Program.cs

示例6: CallWebApiAddReunion

        public async Task<bool> CallWebApiAddReunion(Reunion reunion, ObservableCollection<Anime> selectedAnime)
        {
            HttpClient client = new HttpClient();
            string json = JsonConvert.SerializeObject(reunion);
            HttpContent content = new StringContent(json, Encoding.UTF8, "application/json");
            HttpResponseMessage response = await client.PostAsync("http://scoutome.azurewebsites.net/api/reunions", content);
            if (response.IsSuccessStatusCode)
            {
                //    Pour ajouter les présences  
                for (int i = 0; i < selectedAnime.Count(); i++)
                {
                    Presences pre = new Presences();
                    pre.codeReunion = reunion.codeReunion;
                    pre.useless = 1;
                    pre.codeAnime = selectedAnime[i].codeAnime;

                    string jsonPresence = JsonConvert.SerializeObject(pre);
                    HttpContent contentPresence = new StringContent(jsonPresence, Encoding.UTF8, "application/json");
                    HttpResponseMessage responsefav = await client.PostAsync("http://scoutome.azurewebsites.net/api/presences", contentPresence);
                    if (responsefav.IsSuccessStatusCode)
                    {

                    }
                }

            }
            return false;
        }
开发者ID:GalmOne,项目名称:ScoutomeWinPhone,代码行数:28,代码来源:DataAccessObject.cs

示例7: PostData

 public async Task<Result> PostData(Uri uri, MultipartContent header, StringContent content)
 {
     var httpClient = new HttpClient();
     try
     {
         if (!string.IsNullOrEmpty(AuthenticationToken))
         {
             httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", AuthenticationToken);
         }
         HttpResponseMessage response;
         if (header == null)
         {
             if(content == null) content = new StringContent(string.Empty);
             response = await httpClient.PostAsync(uri, content);
         }
         else
         {
             response = await httpClient.PostAsync(uri, header);
         }
         var responseContent = await response.Content.ReadAsStringAsync();
         return new Result(response.IsSuccessStatusCode, responseContent);
     }
     catch (Exception ex)
     {
         throw new WebException("Kinder Chat API Error: Service error", ex);
     }
 }
开发者ID:richardboegli,项目名称:KinderChat,代码行数:27,代码来源:WebManager.cs

示例8: GetAccessToken

        public static async Task<string> GetAccessToken(string username, string password)
        {
            try
            {
                var handler = new HttpClientHandler
                {
                    AutomaticDecompression = DecompressionMethods.GZip,
                    AllowAutoRedirect = false
                };

                using (var tempHttpClient = new HttpClient(handler))
                {
                    //Get session cookie
                    var sessionResp = await tempHttpClient.GetAsync(Resources.PtcLoginUrl);
                    var data = await sessionResp.Content.ReadAsStringAsync();
                    var lt = JsonHelper.GetValue(data, "lt");
                    var executionId = JsonHelper.GetValue(data, "execution");

                    //Login
                    var loginResp = await tempHttpClient.PostAsync(Resources.PtcLoginUrl,
                        new FormUrlEncodedContent(
                            new[]
                            {
                                new KeyValuePair<string, string>("lt", lt),
                                new KeyValuePair<string, string>("execution", executionId),
                                new KeyValuePair<string, string>("_eventId", "submit"),
                                new KeyValuePair<string, string>("username", username),
                                new KeyValuePair<string, string>("password", password)
                            }));

                    var decoder = new WwwFormUrlDecoder(loginResp.Headers.Location.Query);
                    var ticketId = decoder.GetFirstValueByName("ticket");
                    if (string.IsNullOrEmpty(ticketId))
                        throw new PtcOfflineException();

                    //Get tokenvar 
                    var tokenResp = await tempHttpClient.PostAsync(Resources.PtcLoginOauth,
                        new FormUrlEncodedContent(
                            new[]
                            {
                                new KeyValuePair<string, string>("client_id", "mobile-app_pokemon-go"),
                                new KeyValuePair<string, string>("redirect_uri",
                                    "https://www.nianticlabs.com/pokemongo/error"),
                                new KeyValuePair<string, string>("client_secret",
                                    "w8ScCUXJQc6kXKw8FiOhd8Fixzht18Dq3PEVkUCP5ZPxtgyWsbTvWHFLm2wNY0JR"),
                                new KeyValuePair<string, string>("grant_type", "refresh_token"),
                                new KeyValuePair<string, string>("code", ticketId)
                            }));

                    var tokenData = await tokenResp.Content.ReadAsStringAsync();
                    decoder = new WwwFormUrlDecoder(tokenData);
                    return decoder.GetFirstValueByName("access_token");
                }
            }
            catch (Exception)
            {
                return string.Empty;
            }
        }
开发者ID:ZunlabResearch,项目名称:PoGo-UWP,代码行数:59,代码来源:PtcLogin.cs

示例9: GetAccessToken

        public static async Task<string> GetAccessToken(string username, string password)
        {
            var handler = new HttpClientHandler
            {
                AutomaticDecompression = DecompressionMethods.GZip,
                AllowAutoRedirect = false
            };

            using (var tempHttpClient = new HttpClient(handler))
            {
                //Get session cookie
                var sessionResp = await tempHttpClient.GetAsync(Resources.PtcLoginUrl);
                var data = await sessionResp.Content.ReadAsStringAsync();
                if (data == null) throw new PtcOfflineException();

                if (sessionResp.StatusCode == HttpStatusCode.InternalServerError || data.Contains("<title>Maintenance"))
                    throw new PtcOfflineException();

                var lt = JsonHelper.GetValue(data, "lt");
                var executionId = JsonHelper.GetValue(data, "execution");

                //Login
                var loginResp = await tempHttpClient.PostAsync(Resources.PtcLoginUrl,
                    new FormUrlEncodedContent(
                        new[]
                        {
                            new KeyValuePair<string, string>("lt", lt),
                            new KeyValuePair<string, string>("execution", executionId),
                            new KeyValuePair<string, string>("_eventId", "submit"),
                            new KeyValuePair<string, string>("username", username),
                            new KeyValuePair<string, string>("password", password)
                        }));

                if (loginResp.Headers.Location == null)
                    throw new PtcOfflineException();

                var ticketId = HttpUtility.ParseQueryString(loginResp.Headers.Location.Query)["ticket"];
                if (ticketId == null)
                    throw new PtcOfflineException();

                //Get tokenvar 
                var tokenResp = await tempHttpClient.PostAsync(Resources.PtcLoginOauth,
                    new FormUrlEncodedContent(
                        new[]
                        {
                            new KeyValuePair<string, string>("client_id", "mobile-app_pokemon-go"),
                            new KeyValuePair<string, string>("redirect_uri",
                                "https://www.nianticlabs.com/pokemongo/error"),
                            new KeyValuePair<string, string>("client_secret",
                                "w8ScCUXJQc6kXKw8FiOhd8Fixzht18Dq3PEVkUCP5ZPxtgyWsbTvWHFLm2wNY0JR"),
                            new KeyValuePair<string, string>("grant_type", "refresh_token"),
                            new KeyValuePair<string, string>("code", ticketId)
                        }));

                var tokenData = await tokenResp.Content.ReadAsStringAsync();
                return HttpUtility.ParseQueryString(tokenData)["access_token"];
            }
        }
开发者ID:ChainRythm,项目名称:Pokemon-Go-Bot,代码行数:58,代码来源:PtcLogin.cs

示例10: WebClientServerTestAsync

        async public Task WebClientServerTestAsync()
        {
            HttpConfiguration configuration = new HttpConfiguration();
            HotsApi.Configure(configuration);

            using (HttpServer server = new HttpServer(configuration))
            {
                using (HttpClient client = new HttpClient(server))
                {
                    client.BaseAddress = new Uri("http://host/api/");
                    string uri = "hero/";
                    HttpResponseMessage response = await client.GetAsync(uri);

                    Assert.IsTrue(response.IsSuccessStatusCode);
                    string responseContent = await response.Content.ReadAsStringAsync();
                    Debug.WriteLine(responseContent);

                    // Get Hero Types
                    uri = "herotype/";
                    response = await client.GetAsync(uri);
                    Assert.IsTrue(response.IsSuccessStatusCode);
                    responseContent = await response.Content.ReadAsStringAsync();
                    Dictionary<string, string> heroTypes = JsonConvert
                        .DeserializeObject<IdName[]>(responseContent)
                        .ToDictionary(kv => kv.Id, kv => kv.Name);
                    Debug.WriteLine(responseContent);

                    // Get Hero States
                    uri = "herostate/";
                    response = await client.GetAsync(uri);
                    Assert.IsTrue(response.IsSuccessStatusCode);
                    responseContent = await response.Content.ReadAsStringAsync();
                    Dictionary<string, string> heroStates = JsonConvert
                        .DeserializeObject<IdName[]>(responseContent)
                        .ToDictionary(kv => kv.Id, kv => kv.Name);
                    Debug.WriteLine(responseContent);

                    // Create a Hero
                    uri = $"hero?name=heroA&type={heroTypes.Keys.First()}&price=5";
                    StringContent requestContent = new StringContent(string.Empty, Encoding.UTF8, "application/json");
                    response = await client.PostAsync(uri, requestContent);

                    Assert.IsTrue(response.IsSuccessStatusCode);
                    responseContent = await response.Content.ReadAsStringAsync();
                    IdName hero = JsonConvert.DeserializeObject<IdName>(responseContent);
                    Debug.WriteLine(responseContent);

                    // Add A Free-To-Play period
                    uri = $"freetoplayperiod?hero={hero.Id}&begin=2016%2F10%2F10&end=2016%2F10%2F17";
                    requestContent = new StringContent(string.Empty, Encoding.UTF8, "application/json");
                    response = await client.PostAsync(uri, requestContent);

                    Assert.IsTrue(response.IsSuccessStatusCode);
                    responseContent = await response.Content.ReadAsStringAsync();
                    Debug.WriteLine(responseContent);
                }
            }
        }
开发者ID:sthiakos,项目名称:General,代码行数:58,代码来源:WebClientTest.cs

示例11: Reset

 public async Task Reset()
 {
     using (var client = new HttpClient())
     {
         var response = await client.PostAsync(_shoppingCartBaseUrl + "?reset=true",null);
         response.EnsureSuccessStatusCode();
         response = await client.PostAsync(_ordersBaseUrl + "?reset=true", null);
         response.EnsureSuccessStatusCode();
     }
 }
开发者ID:stevenh77,项目名称:ItineraryHunter-Win8,代码行数:10,代码来源:ResetOrdersAndShoppingCartServiceStateProxy.cs

示例12: CreateProcessAsync

		/// <summary>
		/// 
		/// </summary>
		/// <param name="url"></param>
		/// <exception cref="UnauthorizedAccessException"></exception>
		/// <returns></returns>
		public async Task<ScannerProcess> CreateProcessAsync(string url)
		{
			if (this.Token == null)
				throw new UnauthorizedAccessException("Empty token!");
			else
				this.Token.Validate();

			using (HttpClient client = new HttpClient())
			{
				client.SetCopyleaksClient(HttpContentTypes.Json, this.Token);

				CreateCommandRequest req = new CreateCommandRequest() { URL = url };

				HttpResponseMessage msg;
				if (File.Exists(url))
				{
					FileInfo localFile = new FileInfo(url);
					// Local file. Need to upload it to the server.

					using (var content = new MultipartFormDataContent("Upload----" + DateTime.UtcNow.ToString(CultureInfo.InvariantCulture)))
					{
						using (FileStream stream = File.OpenRead(url))
						{
							content.Add(new StreamContent(stream, (int)stream.Length), "document", Path.GetFileName(url));
							msg = client.PostAsync(Resources.ServiceVersion + "/detector/create-by-file", content).Result;
						}
					}
				}
				else
				{
					// Internet path. Just submit it to the server.
					HttpContent content = new StringContent(
						JsonConvert.SerializeObject(req),
						Encoding.UTF8,
						HttpContentTypes.Json);
					msg = client.PostAsync(Resources.ServiceVersion + "/detector/create-by-url", content).Result;
				}

				if (!msg.IsSuccessStatusCode)
				{
					var errorJson = await msg.Content.ReadAsStringAsync();
					var errorObj = JsonConvert.DeserializeObject<BadResponse>(errorJson);
					if (errorObj == null)
						throw new CommandFailedException(msg.StatusCode);
					else
						throw new CommandFailedException(errorObj.Message, msg.StatusCode);
				}

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

				CreateResourceResponse response = JsonConvert.DeserializeObject<CreateResourceResponse>(json);
				return new ScannerProcess(this.Token, response.ProcessId);
			}
		}
开发者ID:eladbitton,项目名称:.NET-API,代码行数:60,代码来源:Detector.cs

示例13: chamarServio

        static async Task chamarServio()
        {
            using (var RESTClient = new HttpClient())
            {
                //RESTClient.BaseAddress = new Uri("http://localhost:2893/");

                StringBuilder novoProposta = new StringBuilder();
                novoProposta.Append("<Proposta xmlns=\"http://sclovers.com/Proposta\">");
                novoProposta.Append("<NomeCliente>Maria</NomeCliente>");
                novoProposta.Append("<DescricaoProposta>Minha proposta é R$ 15,00</DescricaoProposta>");
                novoProposta.Append("<DataHoraEnviada>2014-10-30</DataHoraEnviada>");
                novoProposta.Append("</Proposta>");
                
                HttpResponseMessage respPOST = await RESTClient.PostAsync(
                    new Uri("http://localhost:2893/Proposta.svc/enviarProposta"),
                    new StringContent(novoProposta.ToString(), Encoding.UTF8, "application/xml"));
                Console.WriteLine(respPOST.StatusCode);

                novoProposta.Clear();
                novoProposta.Append("<Proposta xmlns=\"http://sclovers.com/Proposta\">");
                novoProposta.Append("<NomeCliente>João</NomeCliente>");
                novoProposta.Append("<DescricaoProposta>Minha proposta é R$ 15,00</DescricaoProposta>");
                novoProposta.Append("<DataHoraEnviada>2014-10-30</DataHoraEnviada>");                
                novoProposta.Append("</Proposta>");
                
                respPOST = await RESTClient.PostAsync(
                    new Uri("http://localhost:2893/Proposta.svc/enviarProposta"),
                    new StringContent(novoProposta.ToString(), Encoding.UTF8, "application/xml"));
                Console.WriteLine(respPOST.StatusCode);

                HttpResponseMessage resp = 
                    await RESTClient.GetAsync(new Uri("http://localhost:2893/Proposta.svc/listaPropostaJson"));

                if (resp.IsSuccessStatusCode)
                {
                    Stream stream;
                    stream = await resp.Content.ReadAsStreamAsync();

                    DataContractJsonSerializer dataJson = new DataContractJsonSerializer(typeof(Proposta[]));
                    Proposta[] propostas = (Proposta[])dataJson.ReadObject(stream);

                    foreach (Proposta item in propostas)
                    {
                        Console.WriteLine("Id: {0}", item.Id);
                        Console.WriteLine("Nome: {0}", item.NomeCliente);
                        Console.WriteLine("Proposta: {0}", item.DescricaoProposta);
                        Console.WriteLine("Data: {0}", item.DataHoraEnviada);
                    }
                }
                Console.WriteLine(resp.StatusCode);
            }
        }
开发者ID:lhlima,项目名称:CollaborationProjects,代码行数:52,代码来源:Program.cs

示例14: Execute

        public override IEnumerable<LocalizedString> Execute(WorkflowContext workflowContext, ActivityContext activityContext) {
            var url = activityContext.GetState<string>("Url");
            var verb = (activityContext.GetState<string>("Verb") ?? "GET").ToUpper();
            var headers = activityContext.GetState<string>("Headers");
            var formValues = activityContext.GetState<string>("FormValues") ?? "";

            using (var httpClient = new HttpClient {BaseAddress = new Uri(url)}) {
                HttpResponseMessage response;

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

                if (!String.IsNullOrWhiteSpace(headers)) {
                    foreach (var header in ParseKeyValueString(headers)) {
                        httpClient.DefaultRequestHeaders.Add(header.Key, header.Value);
                    }
                }

                switch (verb) {
                    default:
                    case "GET":
                        response = httpClient.GetAsync("").Result;
                        break;
                    case "POST":
                        var format = activityContext.GetState<string>("FormFormat");

                        switch (format) {
                            default:
                            case "KeyValue":
                                var form = ParseKeyValueString(formValues);
                                response = httpClient.PostAsync("", new FormUrlEncodedContent(form)).Result;
                                break;
                            case "Json":
                                var json = formValues.Replace("((", "{").Replace("))", "}");
                                response = httpClient.PostAsync("", new StringContent(json, Encoding.UTF8, "application/json")).Result;
                                break;
                        }
                        
                        break;
                }
                
                workflowContext.SetState("WebRequestResponse", response.Content.ReadAsStringAsync().Result);

                if (response.IsSuccessStatusCode)
                    yield return T("Success");
                else
                    yield return T("Error");
            }
        }
开发者ID:RasterImage,项目名称:Orchard,代码行数:48,代码来源:WebRequestActivity.cs

示例15: RunClientServerSample

    private static async Task RunClientServerSample(Uri server)
    {
      using(var httpClient = new HttpClient())
      {
        {
          var result = await httpClient.PostAsync($"{server}CreateArticle.command", new StringContent(@"{
  ""CQRSMicroservices.Articles.CreateArticleCommand"" : {
    ""ArticleId"": ""d0174342-71b0-4deb-b5b8-d1064d07ec3c"",
    ""Description"": ""iPhone 6S 64 GB Space Gray"",
    ""Price"": 850.99,
  }
}"));
          var resultContent = await result.Content.ReadAsStringAsync();
          System.Console.WriteLine(resultContent);
        }
        {
          var result = await httpClient.PostAsync($"{server}CreateCustomer.command", new StringContent(@"{
  ""CQRSMicroservices.Customers.CreateCustomerCommand"" : {
    ""CustomerId"": ""14b2e8ec-31e2-4a19-b40a-6f77ae3cf4f0"",
    ""Name"": ""AFAS Software""
  }
}"));
          var resultContent = await result.Content.ReadAsStringAsync();
          System.Console.WriteLine(resultContent);
        }
        {
          var result = await httpClient.PostAsync($"{server}SellArticle.command", new StringContent(@"{
  ""CQRSMicroservices.Articles.SellArticleCommand"" : {
    ""ArticleId"": ""d0174342-71b0-4deb-b5b8-d1064d07ec3c"",
    ""CustomerId"": ""14b2e8ec-31e2-4a19-b40a-6f77ae3cf4f0""
  }
}"));
          var resultContent = await result.Content.ReadAsStringAsync();
          System.Console.WriteLine(resultContent);
        }

        System.Console.WriteLine("Wait a second or two to let the QueryModelBuilder catch up...");
        await Task.Delay(2000);

        {
          var result = await httpClient.GetAsync($"{server}CQRSMicroservices/Articles/GetArticleQuery.query?ArticleId=d0174342-71b0-4deb-b5b8-d1064d07ec3c");
          var document = await result.Content.ReadAsStringAsync();
          System.Console.WriteLine(document);
        }

        System.Console.ReadKey();
      }
    }
开发者ID:AFASResearch,项目名称:CQRS-Playground,代码行数:48,代码来源:Program.cs


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