美文网首页
HttpClient 示例

HttpClient 示例

作者: 寻找无名的特质 | 来源:发表于2022-05-10 06:25 被阅读0次

使用HttpClient调用Web Api的示例代码如下:

using System;
using SendPlanConsole;
using Newtonsoft.Json;
using System.Net.Http.Headers;
using System.Net;

// See https://aka.ms/new-console-template for more information
var plan= new PlanDto{PlanId =  Guid.NewGuid().ToString(),PlanName="Test",PlanDescription="Test plan"};
var content= JsonConvert.SerializeObject(plan);
var url="http://localhost:5197/ApprovePlan/SaveInputPlan";
using(var client=new HttpClient())
{
    HttpContent httpContent = new StringContent(content);
    httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
    httpContent.Headers.ContentType.CharSet = "utf-8";
    HttpResponseMessage responseMessage = await client.PostAsync(url, httpContent);
    Console.WriteLine(await responseMessage.Content.ReadAsStringAsync());
}
Console.WriteLine(plan.ToString());

这里需要注意的是名称空间,需要使用System.Net,然后是Headers.ContentType 的设置,类型为MediaTypeHeaderValue,名称空间为System.Net.Http.Headers,这里需要设置为application/json,Api端的代码如下:

     [HttpPost("SaveInputPlan")]
        public string SaveInputPlan(PlanDto plan)
        {
            var content = JsonConvert.SerializeObject(plan);
            System.IO.File.WriteAllText("InputPlans/" + plan.PlanId + ".json", content);
            return "";
        }

相关文章

网友评论

      本文标题:HttpClient 示例

      本文链接:https://www.haomeiwen.com/subject/uccpsrtx.html