.net core HttpClient Post json参数请求

被请求的接口代码如下:

    //被请求接口
    // POST api/values
    [HttpPost]
    public MyProperty Post([FromBody] MyProperty value)
    {
        return value;
    }
    
    //参数
    public class MyProperty
    {
        public int ID { get; set; }
        public string Name { get; set; }
    }
    

方法一:

1、使用HttpClient的PostAsync方法发送Json数据请求


        public class JsonContent : StringContent
        {
            public JsonContent(object obj) :
            base(JsonConvert.SerializeObject(obj), Encoding.UTF8, "application/json")
            { }
        }

2、发送PostAsync请求

 HttpClient httpClient = new HttpClient();//http对象
 HttpResponseMessage response = httpClient.PostAsync("http://localhost:59958/api/values", new JsonContent(new { ID = 222, Name = "测试2" })).Result;
 string result = response.Content.ReadAsStringAsync().Result;

方法二:

1、使用HttpClient的PostAsync方法发送Json数据请求

   public class JsonContent : StringContent
   {
        public JsonContent(object obj) :
           base(JsonConvert.SerializeObject(obj), Encoding.UTF8, "application/json")
          { }
   }

2、封装

        public static string HttpClientPost(string url, object datajson)
        {
            HttpClient httpClient = new HttpClient();//http对象
            //表头参数
            httpClient.DefaultRequestHeaders.Accept.Clear();
            httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            //转为链接需要的格式
            HttpContent httpContent = new JsonContent(datajson);
            //请求
            HttpResponseMessage response = httpClient.PostAsync(url, httpContent).Result;
            if (response.IsSuccessStatusCode)
            {
                Task t = response.Content.ReadAsStringAsync();
                if (t != null)
                {
                    return t.Result;
                }
            }
            return "";
        }

3、参数

 public class MyProperty
 {
    public int ID { get; set; }
    public string Name { get; set; }
}

4、调用

   MyProperty myProperty = new MyProperty();
   myProperty.ID = 666;
   myProperty.Name = "Tom猫";

   var result = HttpClientPost("http://localhost:59958/api/values", myProperty);
   Console.WriteLine(result);

 

你可能感兴趣的:(C#)