地址: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 = , 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 = ;
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();
} }

谢谢浏览!

一个 Github 上使用 HttpClient 的 Sample的更多相关文章

  1. 安利一个github上面的一个神级库thefuck,Linux命令敲错了,没关系,自动纠正你的命令

    没错就是这么神奇,名字相当噶性,thefuck.当你命令输入错误不要怕,直接来一句fuck,自动纠正你输入的命令. 在你输入错误的命令的时候,忍俊不禁的想来一句fuck,没错你不仅可以嘴上说,命令里面 ...

  2. 跑github上的Symfony项目遇到的问题

    Loading composer repositories with package information Installing dependencies (including require-de ...

  3. 用Jekyll在github上写博客——《搭建一个免费的,无限流量的Blog》的注脚

    本来打算买域名,买空间,用wordpress写博客的.后来问了一个师兄,他说他是用github的空间,用Jekyll写博客,说很多人都这么做.于是我就研究了一下. 比较有价值的文章有这么几篇: htt ...

  4. 如何在github上创建一个Repository (Windows)

    一种方式是利用Github for windows工具 来操作github,这个是我推荐的方式 1 请先下载一个工具Github for windows,下载地址为:https://windows.g ...

  5. https://github.com/coolnameismy/BabyBluetooth github上的一个ios 蓝牙4.0的库并带文档和教程

    The easiest way to use Bluetooth (BLE )in ios,even bady can use. 简单易用的蓝牙库,基于CoreBluetooth的封装,并兼容ios和 ...

  6. 在github上搭建一个静态的个人网站

    说一下大概步骤 1.创建一个新仓库 仓库名必须是你的用户名+github.io后缀 例:用户名:tom 仓库名就要是:tom.github.io (这里具体步骤可以自己百度一下) 2.创建好仓库我们该 ...

  7. git操作+一个本地项目推到github上+注意

    git init 创建新文件夹,打开,然后执行以创建新的 git 仓库. git config --global user.name "xxx" git config --glob ...

  8. 在Android上山寨了一个Ios9的LivePhotos,放Github上了

    9月10号的凌晨上演了一场IT界的春晚,相信很多果粉(恩,如果你指坚果,那我也没办法了,是在下输了)都熬夜看了吧,看完打算去医院割肾了吧.在发布会上发布了游戏机 Apple TV,更大的砧板 Ipad ...

  9. 将本地的一个新项目上传到GitHub上新建的仓库中去

    转载: 如何将本地的一个新项目上传到GitHub上新建的仓库中去 踩过的坑: 1.在git push时报错 error: RPC failed; curl 56 SSL read: error:000 ...

随机推荐

  1. 在centos7 中docker info报错docker bridge-nf-call-iptables is disabled 的解决方法

    在centos7中安装好docker以后,启动成功,运行命令 docker info ,报错: [root@iz2ze2bn5x2wqxdeq65wlpz ~]# docker info Client ...

  2. rt-thread can

    rt-thread stm32f10x-HAL can的驱动和应用.源码暂时还不支持,自己通过F4修改了一版 源码地址:https://gitee.com/gitee.thomas/rt_can rt ...

  3. 深入浅出讲解低功耗蓝牙(BLE)协议栈

    详解BLE连接建立过程https://www.cnblogs.com/iini/p/8972635.html 详解BLE 空中包格式—兼BLE Link layer协议解析https://www.cn ...

  4. LeeCode——Second Highest Salary

    Write a SQL query to get the second highest salary from the Employee table. +----+--------+ | Id | S ...

  5. hexo笔记

    目录 hexo 常用指令 站内文章跳转 hexo安装 NexT主题 默认主题 评论插件-gitalk 修改内容区宽度 添加文章阴影 文章摘要设置 一篇文章多个 categories hexo的一些配置 ...

  6. 3-1 Pandas-概述

    Pandas章节应用的数据可以在以下链接下载: https://files.cnblogs.com/files/AI-robort/Titanic_Data-master.zip Pandas:数据分 ...

  7. 自启动脚本/etc/rc.local文件

    /etc目录下 rc文件均是/rc.d目录中的链接,需要添加自启,只要编辑/etc/rc.local即可

  8. Pyqt5开发一款小工具(翻译小助手)

    翻译小助手 开发需求 首先五月份的时候,正在学习爬虫的中级阶段,这时候肯定要接触到js逆向工程,于是上网找了一个项目来练练手,这时碰巧有如何进行对百度翻译的API破解思路,仿造网上的思路,我摸索着完成 ...

  9. 便宜的回文 (USACO 2007)(c++)

    2019-08-21便宜的回文(USACO 2007) 内存限制:128 MiB 时间限制:1000 ms 标准输入输出 题目类型:传统 评测方式:文本比较 题目描述 追踪每头奶牛的去向是一件棘手的任 ...

  10. linux (06) redis安装

    redis安装 一.在linux安装redis,通过源码编译安装redis 1.下载源码包 wget http://download.redis.io/releases/redis-4.0.10.ta ...