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


C# HttpClient.PostAsJsonAsync方法代码示例

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


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

示例1: Process

        private async static void Process()
        {
            //获取当前联系人列表
            HttpClient httpClient = new HttpClient();
            HttpResponseMessage response = await httpClient.GetAsync("http://localhost/selfhost/api/contacts");
            IEnumerable<Contact> contacts = await response.Content.ReadAsAsync<IEnumerable<Contact>>();
            Console.WriteLine("当前联系人列表:");
            ListContacts(contacts);

            //添加新的联系人
            Contact contact = new Contact { Name = "王五", PhoneNo = "0512-34567890", EmailAddress = "[email protected]" };
            await httpClient.PostAsJsonAsync<Contact>("http://localhost/selfhost/api/contacts", contact);
            Console.WriteLine("添加新联系人“王五”:");
            response = await httpClient.GetAsync("http://localhost/selfhost/api/contacts");
            contacts = await response.Content.ReadAsAsync<IEnumerable<Contact>>();
            ListContacts(contacts);

            //修改现有的某个联系人
            response = await httpClient.GetAsync("http://localhost/selfhost/api/contacts/001");
            contact = (await response.Content.ReadAsAsync<IEnumerable<Contact>>()).First();
            contact.Name = "赵六";
            contact.EmailAddress = "[email protected]";
            await httpClient.PutAsJsonAsync<Contact>("http://localhost/selfhost/api/contacts/001", contact);
            Console.WriteLine("修改联系人“001”信息:");
            response = await httpClient.GetAsync("http://localhost/selfhost/api/contacts");
            contacts = await response.Content.ReadAsAsync<IEnumerable<Contact>>();
            ListContacts(contacts);

            //删除现有的某个联系人
            await httpClient.DeleteAsync("http://localhost/selfhost/api/contacts/002");
            Console.WriteLine("删除联系人“002”:");
            response = await httpClient.GetAsync("http://localhost/selfhost/api/contacts");
            contacts = await response.Content.ReadAsAsync<IEnumerable<Contact>>();
            ListContacts(contacts);
        }
开发者ID:chenboyi081,项目名称:asp-net-web-api-2-samples,代码行数:35,代码来源:Program.cs

示例2: InvokeRequestResponseService

    static async Task InvokeRequestResponseService()
    {
        using (var client = new HttpClient())
        {
            var scoreRequest = new
            {

                Inputs = new Dictionary<string, StringTable>() { 
                        { 
                            "input1", 
                            new StringTable() 
                            {
                                ColumnNames = new string[] {"age", "workclass", "fnlwgt", "education", "education-num", "marital-status", "occupation", "relationship", "race", "sex", "capital-gain", "capital-loss", "hours-per-week", "native-country", "income"},
                                Values = new string[,] {  { "28", "Private", "338409", "Bachelors", "13", "Married-civ-spouse", "Prof-specialty", "Wife", "Black", "Female", "0", "0", "40", "Cuba", "value" }  }
                            }
                        },
                                        },

                GlobalParameters = new Dictionary<string, string>()
                {
                }
            };
            const string apiKey = "ipzYJXleUG6BTzkAcTfrrBLcvEE7XLFs28hVOHRXsZCMDEIqyRoHBQDV16TJB8LoTq7oY4d9mgmXPKsLq6nn+w=="; // Replace this with the API key for the web service
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);

            client.BaseAddress = new Uri("https://ussouthcentral.services.azureml.net/workspaces/f05b36fa1fa84506a4f7d1fd20e5b879/services/5ed21bc4d8134ab7a6984eb9a5660ad1/execute?api-version=2.0&details=true");

            // WARNING: The 'await' statement below can result in a deadlock if you are calling this code from the UI thread of an ASP.Net application.
            // One way to address this would be to call ConfigureAwait(false) so that the execution does not attempt to resume on the original context.
            // For instance, replace code such as:
            //      result = await DoSomeTask()
            // with the following:
            //      result = await DoSomeTask().ConfigureAwait(false)


            HttpResponseMessage response = await client.PostAsJsonAsync("", scoreRequest);

            if (response.IsSuccessStatusCode)
            {
                string result = await response.Content.ReadAsStringAsync();
                Console.WriteLine("Result: {0}", result);
            }
            else
            {
                Console.WriteLine(string.Format("The request failed with status code: {0}", response.StatusCode));

                // Print the headers - they include the requert ID and the timestamp, which are useful for debugging the failure
                Console.WriteLine(response.Headers.ToString());

                string responseContent = await response.Content.ReadAsStringAsync();
                Console.WriteLine(responseContent);
            }
        }
    }
开发者ID:cacosta1a,项目名称:Appnew_test,代码行数:54,代码来源:testws.aspx.cs

示例3: MessageAnalysis

    public void MessageAnalysis(string message)
    {
        #region Commented Old Version
         //string responseXml = "";
         // pass it to some service
         //var client=new HttpClient();
         //string url = ConfigurationManager.AppSettings["ServiceUrl"].ToString(CultureInfo.InvariantCulture);
         //client.BaseAddress = new Uri(url);
         //client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

         //var irequest = new UssdRequestMessage() { TransactionId = "53635424", MSISDN = "911734365", TransactionTime = DateTime.UtcNow.ToString("o"), response = false, USSDServiceCode = "809", USSDRequestString = "*809#" };
         ////HttpResponseMessage response = client.GetAsync("api/Communication/GetResponse?request=" + message).Result;
         //HttpResponseMessage iresponse = client.PostAsJsonAsync("api/communication/GetResponse", irequest).Result;
         //var cont = iresponse.Content.ReadAsAsync<UssdResponseMessage>();

         ////HttpResponseMessage response = client.GetAsync("api/Communication/GetResponse?request=" + message).Result;
         ////HttpResponseMessage response = client.PostAsJsonAsync("api/communication/GetResponse", message).Result;
         //if (iresponse.IsSuccessStatusCode)
         //{
         //    var content = iresponse.Content.ReadAsAsync<UssdResponseMessage>();
         //    responseXml = new USSDXMLWriter(content.Result).GenerateXml();
         //}
         //else
         //{
         //    var request = new USSDXMLReader(message).GenerateMessageObject();
         //    var fault = new FaultResponse() {TransactionId = request.TransactionId,FaultCode = "303",FaultString = "Error occured processing the request",TransactionTime = DateTime.UtcNow};
         //    responseXml = new USSDXMLWriter(fault).GenerateXml();
         //}
         //var request = new USSDXMLReader(message).GenerateMessageObject();
         //var response = new Gate().GetResponse(request);
         //responseXml = new USSDXMLWriter(response).GenerateXml();
        #endregion
         var client = new HttpClient();
         string url = ConfigurationManager.AppSettings["ServiceUrl"].ToString(CultureInfo.InvariantCulture);
         client.BaseAddress = new Uri(url);
         client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

         string transactionId = "";
         Random random = new Random();
         var trId = random.Next(0, 99999999);
         transactionId = trId.ToString("0000000#");
         //var request = new UssdRequestMessage() { TransactionId = transactionId, MSISDN = "251911734365", TransactionTime = DateTime.UtcNow.ToString("o"), response = false, USSDServiceCode = "809", USSDRequestString = "*809#" };
         var request = new USSDXMLReader(message).GenerateMessageObject();
         var serializer = new JavaScriptSerializer();
         var requestCsv = serializer.Serialize(request);//new CsvHelper().WriteObjectToCsv(request);
         HttpResponseMessage response = client.PostAsJsonAsync("service/api/communication/GetResponse", requestCsv).Result;
         var cont = response.Content.ReadAsStringAsync();

         new UssdSender().XmlRpcCall(cont.Result);//.SendUssdResponse(cont.Result);
    }
开发者ID:behailus,项目名称:geez_ussd,代码行数:50,代码来源:UssdReceiver.cs

示例4: GetResponse

    private UssdResponse GetResponse(object[] parameters)
    {
        var client = new HttpClient();
        string url = ConfigurationManager.AppSettings["ServiceUrl"].ToString(CultureInfo.InvariantCulture);
        client.BaseAddress = new Uri(url);
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        var request = new USSDXMLReader().GetUssdRequest(parameters);
        var serializer = new JavaScriptSerializer();
        var requestCsv = serializer.Serialize(request);//new CsvHelper().WriteObjectToCsv(request);
        HttpResponseMessage response = client.PostAsJsonAsync("service/api/communication/GetResponse", requestCsv).Result;
        var cont = response.Content.ReadAsAsync<object[]>();
        var resul = (object[])cont.Result;
        return new UssdResponse() { TransactionId = resul[0].ToString(), TransactionTime = Convert.ToDateTime(resul[1].ToString()), USSDResponseString = resul[2].ToString().Replace("©","\n"), action = resul[3].ToString(), ResponseCode = Convert.ToInt32(resul[4]) };

        //return new UssdResponse() { TransactionId = "123456", TransactionTime = DateTime.Now, USSDResponseString = "Hello Geez " + rpcStruct["MSISDN"].ToString(), action = "end", ResponseCode = 0 };
    }
开发者ID:behailus,项目名称:geez_ussd,代码行数:16,代码来源:GeezServiceHandler.cs

示例5: RunAsync

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

                // HTTP POST
                var command = new Command() { Id = Guid.NewGuid(), Name = "My Name is Pepper" };

                HttpResponseMessage response = await client.PostAsJsonAsync("api/command", command);
                
                if (response.IsSuccessStatusCode)
                {
                    Console.WriteLine("Sucsesfully posted a command");
                }
            }
        }
开发者ID:ramonsmits,项目名称:supportcode,代码行数:19,代码来源:Program.cs

示例6: Main

        static void Main()
        {
            CookieContainer cookies = new CookieContainer();
            HttpClientHandler handler = new HttpClientHandler();
            handler.CookieContainer = cookies;
            using (var httpClient = new HttpClient(handler))
            {
                var response = httpClient.PostAsJsonAsync(
                    POST,
                    new {Username = "User2", Password = "asdf" },
                    CancellationToken.None
                ).Result;
                response.EnsureSuccessStatusCode();
                bool success = response.IsSuccessStatusCode;
                Console.WriteLine("1: " + response.Headers.GetValues("Set-Cookie").FirstOrDefault());
                if (success)
                {
                    HttpRequestMessage request = new HttpRequestMessage();
                    request.Method = HttpMethod.Get;
                    request.RequestUri = new Uri(GET);

                    if (response.IsSuccessStatusCode)
                    {
                        Console.WriteLine(request.Headers);
                    }
                    var secret = httpClient.GetStringAsync(GET);
                    var h= httpClient.GetAsync(GET);
                    Console.WriteLine(secret.Result);
                }
                else
                {
                    Console.WriteLine("Sorry you provided wrong credentials");
                }
            }

            Console.Read();
        }
开发者ID:ssingh5590,项目名称:WebAPI-client,代码行数:37,代码来源:Program.cs

示例7: Transactie

 private async Task Transactie(String PasID, String RekeningID, int balans)
 {
     System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
     using (var client = new HttpClient(new HttpClientHandler { UseProxy = false, ClientCertificateOptions = ClientCertificateOption.Automatic }))
     {
         client.BaseAddress = new Uri("https://hrsqlapp.tk");
         client.DefaultRequestHeaders.Accept.Clear();
         client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
         var trans = new Transactie() { Balans = balans, PasID = Int32.Parse(PasID), RekeningID = RekeningID, locatie = "HRO" };
         HttpResponseMessage response = await client.PostAsJsonAsync("api/transacties", trans).ConfigureAwait(false);
         if (response.IsSuccessStatusCode)
         {
             //Error.show("SUCCES");
         }
         else
         {
             //Error.show("FAIL");
         }
     }
 }
开发者ID:CHG1731,项目名称:ATM,代码行数:20,代码来源:MainProgram.cs


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