c#中 put方式发送Json数据、post方式、delete方式、get方式、

功能:

      用put方式 发送格式json数据,head中增加数据


1、引用

using System.Runtime.Serialization;
using Newtonsoft.Json;
using System.Net.Http;
using System.Net.Http.Headers;

2、put使用

 string Url = "http://localhost:19543/";
            string Data = JsonConvert.SerializeObject(new
                        {
                            apperot = "3"
                        });
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri(Url);
                client.DefaultRequestHeaders.Add("id", "headtest11");
                var response = client.PutAsJsonAsync("api/values/5", Data).Result;


                if (response.IsSuccessStatusCode)
                {
                    Console.Write("Success");
                }
                else
                    Console.Write("Error");
            }

3、post方式

 using (var client = new HttpClient())  
            {  
                person p = new person { name = "Sourav", surname = "Kayal" };  
                client.BaseAddress = new Uri("http://localhost:1565/");  
                var response = client.PostAsJsonAsync("api/person", p).Result;  
                if (response.IsSuccessStatusCode)  
                {  
                    Console.Write("Success");  
                }  
                else  
                    Console.Write("Error");  
            }   


4、Delete方式

using (var client = new HttpClient())    
{    
    client.BaseAddress = new Uri("http://localhost:1565/");    
    var response = client.DeleteAsync("api/person/10").Result;    
    if (response.IsSuccessStatusCode)    
    {    
        Console.Write("Success");    
    }    
    else    
    Console.Write("Error");    
}  

5、Get方式

 HttpClient client = new HttpClient();  
            client.BaseAddress = new Uri("http://localhost:11129/");   
            // Add an Accept header for JSON format.  
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));   
            // List all Names.  
            HttpResponseMessage response = client.GetAsync("api/Values").Result;  // Blocking call!  
            if (response.IsSuccessStatusCode)  
            {  
                var products = response.Content.ReadAsStringAsync().Result;   
            }  
            else  
            {  
                Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);  
            }   


你可能感兴趣的:(c#,MVC)