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


C# HttpClient.PostAsJsonAsync方法代码示例

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


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

示例1: RunAsync

        static async Task RunAsync()
        {
            using (var client = new HttpClient()) // met het gebruik van using zorgen we ervoor dat alles netjes wordt opgeruimd als je buiten de scope zit. 
            {
                client.BaseAddress = new Uri("http://localhost:50752/"); //de URL waar onze website op draait
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); //we krijgen JSON terug van onze API

                // HTTP GET
                HttpResponseMessage response = await client.GetAsync("api/RekeningsApi/1"); //ik wil de eerste klant ophalen. Deze bevindt zich in de api, de RekeningsApiController en dan nummer 1
                if (response.IsSuccessStatusCode) //Controleren of we geen 404 krijgen, maar iets in de 200-reeks
                {
                    Rekening rekening = await response.Content.ReadAsAsync<Rekening>(); //zetten de response asynchroon om in een rekening-object
                    Console.WriteLine("Rekeningnaam: {0}\tBeschrijving: {1}\tSaldo: {2}", rekening.RekeningNaam, rekening.Beschrijving, rekening.Saldo); //en schrijven deze naar de console
                }
                //Console.ReadKey(); //even op een toets drukken om verder te gaan


                var klantNew = new Klant() { Beschrijving = "willekeurige klant", Name = "John Doe" }; //we maken een nieuwe klant aan en vullen deze meteen met info
                response = await client.PostAsJsonAsync("api/KlantsApi/", klantNew); //we sturen deze nieuwe klant asynchroon naar de api via een HTTP Post

                if (response.IsSuccessStatusCode) //check of we geen 404 of iets dergelijks krijgen
                {
                    //Console.ReadKey();

                }

                // HTTP POST
                //let op: je kan pas een rekening aanmaken als je de klant eerst hebt aangemaakt vanwege je constraints; een rekening die niet bij een klant hoort zou natuurlijk raar zijn.
                
                    var RekeningNew = new Rekening() { Beschrijving = "Nieuw product", RekeningNaam = "zilvervloot-rekening", Saldo = 5000.50, KlantId = 2 };//nieuwe rekening aanmaken

                    response = await client.PostAsJsonAsync("api/RekeningsApi/", RekeningNew);
                    if (response.IsSuccessStatusCode) //check of we geen 404 of iets dergelijks krijgen
                    {
                        Console.WriteLine("klant aangemaakt");

                        /*Console.ReadKey();
                        Uri responseUrl = response.Headers.Location;

                        // HTTP PUT
                        RekeningNew.Saldo = 80;   // Update price
                        response = await client.PutAsJsonAsync(responseUrl, RekeningNew);

                        // HTTP DELETE
                        response = await client.DeleteAsync(responseUrl);*/
                    }
                
            }
        }
开发者ID:BenGroeneveld,项目名称:project-op3,代码行数:50,代码来源:Program.cs

示例2: RunClient

        private static void RunClient()
        {
            // TEST CERTIFICATE ONLY, PLEASE REMOVE WHEN YOU REPLACE THE CERT WITH A REAL CERT
            // Perform the Server Certificate validation
            ServicePointManager.ServerCertificateValidationCallback += Program.RemoteCertificateValidationCallback;

            // set up the client without client certificate
            HttpClient client = new HttpClient();
            client.BaseAddress = _baseAddress;
            
            // set up the client with client certificate
            WebRequestHandler handler = new WebRequestHandler();
            handler.ClientCertificateOptions = ClientCertificateOption.Manual; // this would pick from the Current user store
            handler.ClientCertificates.Add(GetClientCertificate());

            HttpClient clientWithClientCert = new HttpClient(handler);
            clientWithClientCert.BaseAddress = _baseAddress;
            HttpResponseMessage response;

            //// How to post a sample item with success
            SampleItem sampleItem = new SampleItem { Id = 1, StringValue = "hello from a new sample item" };
            response = clientWithClientCert.PostAsJsonAsync("api/sample/", sampleItem).Result;
            response.EnsureSuccessStatusCode();
            Console.WriteLine("Posting the first item returns:\n" + response.Content.ReadAsStringAsync().Result + "\n");
            response.Dispose();

            // How to get all the sample Items, we should see the newly added sample item that we just posted
            response = client.GetAsync("api/sample/").Result;
            response.EnsureSuccessStatusCode();
            Console.WriteLine("Getting all the items returns:\n" + response.Content.ReadAsStringAsync().Result + "\n");
            response.Dispose();

            // How to post another sample item with success
            sampleItem = new SampleItem { Id = 2, StringValue = "hello from a second new sample item" };
            response = clientWithClientCert.PostAsJsonAsync("api/sample/", sampleItem).Result;
            response.EnsureSuccessStatusCode();
            Console.WriteLine("Posting a second item returns:\n" + response.Content.ReadAsStringAsync().Result + "\n");
            response.Dispose();

            // How to get all the sample Items, we should see the two newly added sample item that we just posted
            response = client.GetAsync("api/sample/").Result;
            response.EnsureSuccessStatusCode();
            Console.WriteLine("Getting all the items returns:\n" + response.Content.ReadAsStringAsync().Result + "\n");
            response.Dispose();

            // How to get an sample item with id = 2
            response = client.GetAsync("api/sample/2").Result;
            response.EnsureSuccessStatusCode();
            Console.WriteLine("Getting the second item returns:\n" + response.Content.ReadAsStringAsync().Result + "\n");
            response.Dispose();

            // Posting without client certificate will fail 
            sampleItem = new SampleItem { Id = 3, StringValue = "hello from a new sample item" };
            response = client.PostAsJsonAsync("api/sample/", sampleItem).Result;
            Console.WriteLine("Posting the third item without client certificate fails:\n" + response.StatusCode + "\n");
            response.Dispose();
        }
开发者ID:wk-j,项目名称:asp-samples,代码行数:57,代码来源:Program.cs

示例3: SendDataToWebhook

		internal static async Task SendDataToWebhook(Models.BathroomStatusModel bathroomStatus)
		{
			try
			{
				using (var client = new HttpClient())
				{
				
					client.BaseAddress = new Uri("http://nibodev.azurewebsites.net/v1/");
					client.DefaultRequestHeaders.Accept.Clear();
					client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

					HttpResponseMessage response = await client.PostAsJsonAsync("Bathroom/SaveStatus", bathroomStatus);
					response.EnsureSuccessStatusCode();

					if (response.IsSuccessStatusCode)
					{

					}
				}
			}
			catch (Exception ex)
			{
				///TODO
			}
		}
开发者ID:rafaheringer,项目名称:smellOMeter,代码行数:25,代码来源:ApiController.cs

示例4: GetAiCardPlay

 /// <summary>
 /// Get the card that the Ai passed in player will play
 /// </summary>
 /// <param name="hand">The current cards that are in play</param>
 /// <param name="player">The player that will be playing the card</param>
 /// <returns>The card played</returns>
 public async System.Threading.Tasks.Task<Card> GetAiCardPlay(Hand hand, Player player)
 {
     if (_feature.FeatureEnabled(AiSimulation.SimService))
     {
         var sim = new BasicTrumpSimluation();
         using (var client = new HttpClient())
         {
             // translate inputs to the sim object
             var response = await client.PostAsJsonAsync("api/api/BasicTrumpSimulation", sim);
             if (response.IsSuccessStatusCode)
             {
                 var card = response.Content.ReadAsAsync<Dto.AiSimulation.Card>();
                 // map to our card
                 throw new NotImplementedException();
             }
             else
             {
                 // errored out yo
                 throw new NotImplementedException();
             }
         }
     }
     else
     {
         var aiSim = new AiSimulation();
         return aiSim.PlayCard(hand, player);
     }
 }
开发者ID:kevinbuckley,项目名称:firststatedotnet.microservices.10-13-15,代码行数:34,代码来源:EukerGAme.cs

示例5: registerSrvData

 private async void registerSrvData()
 {
     HttpClient client = new HttpClient();
     client.BaseAddress = new Uri(URL);
     HttpResponseMessage response = await client.PostAsJsonAsync("/rest/add/Service", srv).ContinueWith((postTask) => postTask.Result.EnsureSuccessStatusCode());
     this.Close();
 }
开发者ID:Werevector,项目名称:DAT154,代码行数:7,代码来源:RegisterServMaintWindow.xaml.cs

示例6: UpdateLicenses

        public async Task UpdateLicenses()
        {
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri("https://api.dropbox.com");
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Add("Authorization", "Bearer " + txtAccesstoken.Text);
                client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

                var response = await client.PostAsJsonAsync("/1/team/get_info", new Licenses());
                var content = await response.Content.ReadAsStringAsync();

                if (response.StatusCode == System.Net.HttpStatusCode.Conflict)
                {
                    throw new Exception("A 409 error message was returned from Dropbox, this can occur for the following reasons: \n \n 409 No available licenses. \n 409 User is already on the team or has already been invited. \n 409 User is already on another team.");
                }
                else if (response.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    LicensesObj licenses = new JavaScriptSerializer().Deserialize<LicensesObj>(content);
                    lbllicensesavailablenumber.Text = Convert.ToString(licenses.num_licensed_users);
                    lblprovisionedusersnumber.Text = Convert.ToString(licenses.num_provisioned_users);
                }
                else
                {
                    throw new Exception(content.Replace("{", "").Replace("}", "").Replace("\"", " "));
                }
            }
        }
开发者ID:Mbond65,项目名称:DB_usermanager,代码行数:28,代码来源:DeleteUsers.cs

示例7: RunAsync

        private async Task RunAsync()
        {
            var newlog = new IPC.Models.IPCLog();

            newlog.Action = "Check";
            newlog.Error = string.Empty;
            newlog.IPCName = "IPCTest";
            newlog.Time = $"{DateTime.Now.ToShortDateString()}-{DateTime.Now.ToShortTimeString()}";

            string site = @"http://localhost:53226/api";

            string servicesite = string.Format("{0}/{1}/", site, "logging");

            string URI = servicesite;
          

            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri(servicesite);
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                // New code:
                var response = await client.PostAsJsonAsync("api/products", newlog);
                if (response.IsSuccessStatusCode)
                {
                    
                }
            }
        }
开发者ID:leeyinheng,项目名称:IPC.Solution,代码行数:30,代码来源:UnitTestWebApi.cs

示例8: AddArtistJson

        public static void AddArtistJson(HttpClient client)
        {
            client.DefaultRequestHeaders.Accept.Add(new
                MediaTypeWithQualityHeaderValue("application/json"));

            Console.WriteLine("Enter artist name");
            string name = Console.ReadLine();
            Console.WriteLine("Enter artist country");
            string country = Console.ReadLine();
            Console.WriteLine("Enter artist birth date");
            DateTime birthDate = DateTime.ParseExact(Console.ReadLine(), "dd.MM.yyyy", new CultureInfo("en-US"));
            Artist artist = new Artist { Name = name, Country = country, DateOfBirth = birthDate };
            HttpResponseMessage response =
                client.PostAsJsonAsync("api/artists", artist).Result;

            if (response.IsSuccessStatusCode)
            {
                Console.WriteLine("Artist added");
            }
            else
            {
                Console.WriteLine("{0} ({1})",
                    (int)response.StatusCode, response.ReasonPhrase);
            }
        }
开发者ID:vasilkrvasilev,项目名称:WebServices,代码行数:25,代码来源:ArtistCommand.cs

示例9: AddUserAsync

        public async Task AddUserAsync(User user)
        {
            var httpClient = new HttpClient();
            httpClient.BaseAddress = new Uri("http://localhost:1874/", UriKind.RelativeOrAbsolute);
            httpClient.DefaultRequestHeaders.Accept.Clear();
            httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            var JsonData = new User
            {
                FirstName = user.FirstName,
                LastName = user.LastName,
                Email = user.Email,
                Password = user.Password,
                MedicalSpecialites = user.MedicalSpecialites,
                Address = user.Address,
                PhoneNo = user.PhoneNo
            };
            var response = await httpClient.PostAsJsonAsync(new Uri(BaseUrl1), JsonData);


            if (response.IsSuccessStatusCode)
            {
                post = true;

                gizmoUrl = response.Headers.Location.ToString();

                putlink = gizmoUrl;
                id = putlink.Remove(0, 34);
            }
        }
开发者ID:HoussemEddineAbbes,项目名称:MedicalSearch,代码行数:30,代码来源:DataServices.cs

示例10: Intercept

        public void Intercept(IInvocation invocation)
        {
            if (invocation.Method.ReflectedType == null) throw new Exception("Unknown service type");
            var model = new InvocationApiModel
            {
                ServiceName = invocation.Method.ReflectedType.Name,
                MethodName = invocation.Method.Name,
                Parameters = invocation.Arguments
            };

            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri("http://localhost:5000/");
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                HttpResponseMessage response = client.PostAsJsonAsync("invokeMethod", model)
                    .ConfigureAwait(false)
                    .GetAwaiter()
                    .GetResult();

                if (!response.IsSuccessStatusCode) return;

                string result = response.Content.ReadAsStringAsync()
                    .ConfigureAwait(false)
                    .GetAwaiter()
                    .GetResult();
                object returnValue = JsonConvert.DeserializeObject(result, invocation.Method.ReturnType);
                invocation.ReturnValue = returnValue;
            }
        }
开发者ID:mdymel,项目名称:miseco,代码行数:31,代码来源:MethodInterceptor.cs

示例11: RegisterPlugin

        /// <summary>
        /// Register plugin. All plugin must be registered first.
        /// </summary>
        private static void RegisterPlugin()
        {
            var job = new PluginJob
            {
                AssemblyPath = PluginAssemblyPath,
                JobName = "MyAssemblyPluginJob",
                JobGroup = "MyJobGroup"
            };

            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri(Url);
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                var response = client.PostAsJsonAsync("api/plugins/", job).Result;
                string resultStr = response.Content.ReadAsStringAsync().Result;

                dynamic result = JsonConvert.DeserializeObject<dynamic>(resultStr);

                if (result != null)
                {
                    Console.WriteLine(resultStr);
                    _jobId = new Guid(result.id.ToString());
                }
            }
        }
开发者ID:R-Suite,项目名称:R.Scheduler,代码行数:30,代码来源:Program.cs

示例12: RunAsync

        static async Task RunAsync()
        {
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri("http://internal-devchallenge-2-dev.apphb.com/");
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                string guid;
                for (int i = 0; i < 20; i++)
                {
                    guid = Guid.NewGuid().ToString();
                    HttpResponseMessage response = await client.GetAsync("values/" + guid);
                    string result="";
                    if (response.IsSuccessStatusCode)
                    {
                        AAItem item = await response.Content.ReadAsAsync<AAItem>();
                        switch (item.algorithm)
                        {
                            case "IronMan":
                                Algorithms.SortArray(item, false);//check
                                Algorithms.ShiftVowels(item);//check
                                result = Algorithms.AsciiConcat(item);//check
                                result = System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(result));
                                break;
                            case "TheIncredibleHulk":
                                Algorithms.ShiftVowels(item);//check
                                Algorithms.SortArray(item, true);//check
                                result = Algorithms.AsterixConcat(item);//check
                                result = System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(result));
                                break;
                            case "Thor":
                                //1
                                Algorithms.crazy(item);
                                Algorithms.SortArray(item, false);//check
                                Algorithms.AltCase(item);
                                Algorithms.Fib(item);
                                result = Algorithms.AsterixConcat(item);//check
                                result = System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(result));
                                break;
                            case "CaptainAmerica":
                                Algorithms.ShiftVowels(item);//check
                                Algorithms.SortArray(item, true);//check
                                Algorithms.Fib(item);
                                result = Algorithms.AsciiConcat(item);//check
                                result = System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(result));
                                break;
                        }

                        Calculation postval = new Calculation();
                        postval.encodedValue = result;
                        response = await client.PostAsJsonAsync(string.Format("values/{0}/{1}", guid, item.algorithm), postval);
                        Console.WriteLine(i);
                        Console.WriteLine(item.algorithm);
                        AAResponse asdf = await response.Content.ReadAsAsync<AAResponse>();
                        Console.WriteLine(asdf.status);
                        Console.WriteLine(asdf.message);
                    }
                }
            }
        }
开发者ID:b195ex,项目名称:AAChallenge,代码行数:60,代码来源:Program.cs

示例13: Main

        public static void Main()
        {
            var client = new HttpClient
            {
                BaseAddress = new Uri("http://localhost:7661/")
            };

            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            var album = new Album
            {
                Title = "Runaway",
                Year = 1986,
                Producer = "Bon Jovi"
            };

            HttpResponseMessage response = client.PostAsJsonAsync("api/albums", album).Result;
            if (response.IsSuccessStatusCode)
            {
                Console.WriteLine("{0} added!", album.GetType().Name);
            }
            else
            {
                Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
            }
        }
开发者ID:TeeeeeC,项目名称:TelerikAcademy2015-2016,代码行数:25,代码来源:Startup.cs

示例14: PostGreetingJson

 static async Task PostGreetingJson(string greeting)
 {
     var client = new HttpClient();
     HttpResponseMessage response = await client.PostAsJsonAsync
         (_greetingsBaseUri, greeting);
     response.EnsureSuccessStatusCode();
 }
开发者ID:jiantaow,项目名称:AdvDotNet.Samples,代码行数:7,代码来源:Program.cs

示例15: CreateTestAction

        protected async Task<Action> CreateTestAction(string verb = "Created for test goal and activity")
        {
            var session = await Login();

            using (var client = new HttpClient { BaseAddress = new Uri(ServerUrl) })
            {
                client.AcceptJson().AddSessionHeader(session.Id.ToString());
                var action = new Action
                {
                    Verb = verb,
                    Goal =
                        new Goal
                        {
                            Concern = new ConcernMatrix { Coordinates = new Matrix { X = 1, Y = 1 }, Category = 0 },
                            RewardResource =
                                new RewardResourceMatrix { Coordinates = new Matrix { X = 2, Y = 2 }, Category = 0 },
                            Feedback = new GoalFeedback { Threshold = 0, Target = 0, Direction = 0 },
                            Description = "Created for test cases"
                        },
                    Activity = new Activity { Name = "Testing" }
                };
                var actionResponse = await client.PostAsJsonAsync("/api/actions", action);
                Assert.Equal(HttpStatusCode.Created, actionResponse.StatusCode);

                var created = await actionResponse.Content.ReadAsJsonAsync<Action>();

                return created;
            }
        }
开发者ID:playgenhub,项目名称:rage-sga-server,代码行数:29,代码来源:ActionsControllerTest.cs


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