通过HttpClient的方式去Curd数据⭐⭐⭐⭐

在网上看博客的时候,看到这系列的文章,别特帮,强烈推荐

里面有一章节是通过HttpClient的方法去更新数据的,新颖,记录下。

⭐⭐⭐1:创建一个Model数据模型

这个类创建一个数据对象,HttpClient将把它写入HTTP请求体中,也从HTTP响应体中读取它。

class Product 
{ 
    public string Name { get; set; } 
    public double Price { get; set; } 
    public string Category { get; set; } 
}

⭐⭐⭐2:初始化HttpClient

创建一个新的HttpClient实例,并像下面这样初始化它

namespace ProductStoreClient 
{ 
    using System; 
    using System.Collections.Generic; 
    using System.Net.Http; 
    using System.Net.Http.Headers; 

    class Program 
    { 
        static void Main(string[] args) 
        { 
            HttpClient client = new HttpClient(); 
            client.BaseAddress = new Uri("http://localhost:9000/");             // 为JSON格式添加一个Accept报头
            client.DefaultRequestHeaders.Accept.Add( 
                new MediaTypeWithQualityHeaderValue("application/json")); 
        } 
    } 
}
这段代码把基URI设置为“http://localhost:9000/”,并将Accept报头设置为“application/json”,
这是告诉服务器,以JSON格式发送数据

⭐⭐⭐3:获取数据

// List all products.
// 列出所有产品
HttpResponseMessage response = client.GetAsync("api/products").Result;  // Blocking call(阻塞调用)! 
if (response.IsSuccessStatusCode) 
{ 
    // Parse the response body. Blocking!
    // 解析响应体。阻塞!
如果HTTP响应指示成功,响应体便含有一个JSON格式的产品列表。要解析这个列表,需调用ReadAsAsync
var products = response.Content.ReadAsAsync<IEnumerable<Product>>().Result; foreach (var p in products) { Console.WriteLine("{0} {1}; {2}", p.Name, p.Price, p.Category); } } else { Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase); }

GetAsync方法发送HTTP GET请求。正如其名称所暗示的,GetAsync是异步的。它立即返回,不会等待服务器的响应

返回值是一个表示异步操作的Task对象。当该操作完成时,Task.Result属性包含HTTP响应。

重要的是理解,直到请求完成(或超时),采用Result属性的过程是应用程序线程阻塞的

控制台应用程序的阻塞没问题,但是,你决不应该在一个Windows应用程序的UI上做这种事,因为这会阻塞UI去响应用户的输入

再次强调,采用Result属性的过程是线程阻塞的。

⭐⭐⭐4:通过Id,获取数据

// Get a product by ID
// 通过ID获取产品
response = client.GetAsync("api/products/1").Result; 
if (response.IsSuccessStatusCode) 
{ 
    // Parse the response body. Blocking!
    // 解析响应休。阻塞!
    var product = response.Content.ReadAsAsync<Product>().Result; 这里直接就是将返回的数据序列化成Product对象
    Console.WriteLine("{0}	{1};	{2}", product.Name, product.Price, product.Category); 
} 
else 
{ 
    Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase); 
}

⭐⭐⭐5:add data

/ Create a new product
// 创建一个新产品
var gizmo = new Product() { Name = "Gizmo", Price = 100, Category = "Widget" }; 
Uri gizmoUri = null; 

response = client.PostAsJsonAsync("api/products", gizmo).Result; 
if (response.IsSuccessStatusCode) 
{ 
    gizmoUri = response.Headers.Location; 
} 
else 
{ 
    Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase); 
}
⭐⭐⭐PostAsJsonAsync是在System.Net.Http.HttpClientExtensions中定义的一个扩展方法。上述代码与以下代码等效:------------------------
ar product = new Product() { Name = "Gizmo", Price = 100, Category = "Widget" }; 

// Create the JSON formatter.
// 创建JSON格式化器。
MediaTypeFormatter jsonFormatter = new JsonMediaTypeFormatter(); 

// Use the JSON formatter to create the content of the request body.
// 使用JSON格式化器创建请求体内容。
HttpContent content = new ObjectContent<Product>(product, jsonFormatter); 

// Send the request.
// 发送请求。
var resp = client.PostAsync("api/products", content).Result;

Error Handling
错误处理

HttpClient在它接收到一个带有错误代码的HTTP响应时,不会抛出异常。

但是,该响应的StatusCode属性含有状态码。而且,如果其状态是一个成功的状态码(状态码在200-299之间)时,IsSuccessStatusCode属性为true

使用这种模式的前面这个例子为:

HttpResponseMessage response = client.GetAsync("api/products").Result; 
if (response.IsSuccessStatusCode) 
{ 
     // .... 
}
如果你喜欢把错误代码处理成异常,可以调用EnsureSuccessStatusCode方法。这个方法在响应状态不是一个成功的代码时,会抛出一个异常。

try 
{ 
    var resp = client.GetAsync("api/products").Result; 
    resp.EnsureSuccessStatusCode();    // Throw if not a success code. 

    // ... 
} 
catch (HttpRequestException e) 
{ 
    Console.WriteLine(e.Message); 
}
原文地址:https://www.cnblogs.com/ZkbFighting/p/11956068.html