地址: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. MQ选型对比ActiveMQ,RabbitMQ,RocketMQ,Kafka 消息队列框架选哪个?

    最近研究消息队列,发现好几个框架,搜罗一下进行对比,说一下选型说明: 1)中小型软件公司,建议选RabbitMQ.一方面,erlang语言天生具备高并发的特性,而且他的管理界面用起来十分方便.不考虑r ...

  2. 记录vue用 html5+做移动APP 用barcode做扫一扫功能时安卓 的bug(黑屏、错位等等)和解决方法

    最近做项目时,要用到扫一扫二维码的功能,在html5+里面有提供barcode功能,于是照过来用了, 写的代码如下 : 扫码页面: <style lang="less" sc ...

  3. Java的 Annotation 新特性

    对于软件程序的开发经过了三个发展过程: —— 将所有配置相关的内容直接写到代码之中 —— 将配置与代码程序独立,将程序运行的时候根据配置文件进行操作 —— 配置信息对用户透明且无用,将配置信息写回代码 ...

  4. linux下oracle无法删除用户

    Oracle删除用户的提示无法删除当前已连接用户.且无法kill掉用户进程的两种解决方法如下: 1.先锁定用户.然后查询进程号,最后删除对应的进程.在删除对应的用户 SQL>alter user ...

  5. js中console在一行内打印字符串和对象

    在前端开发中,大多数的调试一般都是F12中的console和network中查看请求数据和响应数据,也有一部分人喜欢用debugger. 在开发大一些的项目时,在开发环境下,打开着控制台,切换一下页面 ...

  6. 【原创】Centos 7 升级安装python3.7.4

    1.安装必须的软件 #更新源中包列表 yum -y update #先安装扩展源EPEL 才能安装pip 否则会报错 yum -y install epel-release //解决ssl问题,否则报 ...

  7. 05showLoading配置和 <text>标签的坑 如何发送请求 分享功能和懒加载

    14-电影-列表-需求分析 小程序里面取数据 没有冒号这么一说 加载动画 在对应页面 js文件中 showLoading你可以去看他的配置     // wx.showLoading() 应用在让用户 ...

  8. 虚拟机使用配置固定IP

    首先打开虚拟机 打开xshell5连接虚拟机(比较方便,这里默认设置过Linux的ip,只是不固定) 输入ifconfig,可以查看网管相关配置信息: 然后输入    vi /etc/sysconfi ...

  9. day22_7.26面向对象之封装(接口与抽象)

    一.封装. 封装就是将丑陋复杂的隐式的细节隐藏到内部,对外提供简单的使用接口. 对外隐藏内部实现细节,并提供访问的接口.对内使用self操作. 二.为什么要封装? 对于一个计算机来说,不可能不使用机箱 ...

  10. 两个开源的 Spring Boot + Vue 前后端分离项目

    折腾了一周的域名备案昨天终于搞定了. 松哥第一时间想到赶紧把微人事和 V 部落部署上去,我知道很多小伙伴已经等不及了. 1. 也曾经上过线 其实这两个项目当时刚做好的时候,我就把它们部署到服务器上了, ...