一个 Github 上使用 HttpClient 的 Sample
2018-09-10 18:39 音乐让我说 阅读(790) 评论(0) 编辑 收藏 举报地址:https://github.com/MikeWasson/HttpClientSample
截图:
直接贴代码了:
服务端:
[RoutePrefix("api/products")] public class ProductsController : ApiController { private static ConcurrentDictionary<string, Product> _products = new ConcurrentDictionary<string, Product>(); [Route("{id}", Name = "GetById")] public IHttpActionResult Get(string id) { Product product = null; if (_products.TryGetValue(id, out product)) { return Ok(product); } else { return NotFound(); } } [HttpPost] [Route("")] public IHttpActionResult Post(Product product) { if (product == null) { return BadRequest("Product cannot be null"); } if (!ModelState.IsValid) { return BadRequest(ModelState); } product.Id = Guid.NewGuid().ToString(); _products[product.Id] = product; return CreatedAtRoute("GetById", new { id = product.Id }, product); } [HttpPut] [Route("{id}")] public IHttpActionResult Put(string id, Product product) { if (product == null) { return BadRequest("Product cannot be null"); } if (!ModelState.IsValid) { return BadRequest(ModelState); } if (product.Id != id) { return BadRequest("product.id does not match id parameter"); } if (!_products.Keys.Contains(id)) { return NotFound(); } _products[id] = product; return new StatusCodeResult(HttpStatusCode.NoContent, this); } [HttpDelete] [Route("{id}")] public IHttpActionResult Delete(string id) { Product product = null; _products.TryRemove(id, out product); return new StatusCodeResult(HttpStatusCode.NoContent, this); } }
完毕!
客户端
class Program { static HttpClient client = new HttpClient(); static void ShowProduct(Product product) { Console.WriteLine($"Name: {product.Name}\tPrice: {product.Price}\tCategory: {product.Category}"); } static async Task<Uri> CreateProductAsync(Product product) { HttpResponseMessage response = await client.PostAsJsonAsync("api/products", product); response.EnsureSuccessStatusCode(); // return URI of the created resource. return response.Headers.Location; } static async Task<Product> GetProductAsync(string path) { Product product = null; HttpResponseMessage response = await client.GetAsync(path); if (response.IsSuccessStatusCode) { product = await response.Content.ReadAsAsync<Product>(); } return product; } static async Task<Product> UpdateProductAsync(Product product) { HttpResponseMessage response = await client.PutAsJsonAsync($"api/products/{product.Id}", product); response.EnsureSuccessStatusCode(); // Deserialize the updated product from the response body. product = await response.Content.ReadAsAsync<Product>(); return product; } static async Task<HttpStatusCode> DeleteProductAsync(string id) { HttpResponseMessage response = await client.DeleteAsync($"api/products/{id}"); return response.StatusCode; } static void Main() { RunAsync().Wait(); } static async Task RunAsync() { client.BaseAddress = new Uri("http://localhost:55268/"); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); try { // Create a new product Product product = new Product { Name = "Gizmo", Price = 100, Category = "Widgets" }; var url = await CreateProductAsync(product); Console.WriteLine($"Created at {url}"); // Get the product product = await GetProductAsync(url.PathAndQuery); ShowProduct(product); // Update the product Console.WriteLine("Updating price..."); product.Price = 80; await UpdateProductAsync(product); // Get the updated product product = await GetProductAsync(url.PathAndQuery); ShowProduct(product); // Delete the product var statusCode = await DeleteProductAsync(product.Id); Console.WriteLine($"Deleted (HTTP Status = {(int)statusCode})"); } catch (Exception e) { Console.WriteLine(e.Message); } Console.ReadLine(); } }
谢谢浏览!
作者:音乐让我说(音乐让我说 - 博客园)
出处:http://music.cnblogs.com/
文章版权归本人所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步