一个 Github 上使用 HttpClient 的 Sample
地址: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的更多相关文章
- 安利一个github上面的一个神级库thefuck,Linux命令敲错了,没关系,自动纠正你的命令
没错就是这么神奇,名字相当噶性,thefuck.当你命令输入错误不要怕,直接来一句fuck,自动纠正你输入的命令. 在你输入错误的命令的时候,忍俊不禁的想来一句fuck,没错你不仅可以嘴上说,命令里面 ...
- 跑github上的Symfony项目遇到的问题
Loading composer repositories with package information Installing dependencies (including require-de ...
- 用Jekyll在github上写博客——《搭建一个免费的,无限流量的Blog》的注脚
本来打算买域名,买空间,用wordpress写博客的.后来问了一个师兄,他说他是用github的空间,用Jekyll写博客,说很多人都这么做.于是我就研究了一下. 比较有价值的文章有这么几篇: htt ...
- 如何在github上创建一个Repository (Windows)
一种方式是利用Github for windows工具 来操作github,这个是我推荐的方式 1 请先下载一个工具Github for windows,下载地址为:https://windows.g ...
- https://github.com/coolnameismy/BabyBluetooth github上的一个ios 蓝牙4.0的库并带文档和教程
The easiest way to use Bluetooth (BLE )in ios,even bady can use. 简单易用的蓝牙库,基于CoreBluetooth的封装,并兼容ios和 ...
- 在github上搭建一个静态的个人网站
说一下大概步骤 1.创建一个新仓库 仓库名必须是你的用户名+github.io后缀 例:用户名:tom 仓库名就要是:tom.github.io (这里具体步骤可以自己百度一下) 2.创建好仓库我们该 ...
- git操作+一个本地项目推到github上+注意
git init 创建新文件夹,打开,然后执行以创建新的 git 仓库. git config --global user.name "xxx" git config --glob ...
- 在Android上山寨了一个Ios9的LivePhotos,放Github上了
9月10号的凌晨上演了一场IT界的春晚,相信很多果粉(恩,如果你指坚果,那我也没办法了,是在下输了)都熬夜看了吧,看完打算去医院割肾了吧.在发布会上发布了游戏机 Apple TV,更大的砧板 Ipad ...
- 将本地的一个新项目上传到GitHub上新建的仓库中去
转载: 如何将本地的一个新项目上传到GitHub上新建的仓库中去 踩过的坑: 1.在git push时报错 error: RPC failed; curl 56 SSL read: error:000 ...
随机推荐
- Laravel 运行php artisan serve命令时提示No application encryption key has been specified
创建了新的laravel项目后, 运行提示:No application encryption key has been specified 解决方法: 这个是由于没有配置好 APP_KEY 在终端上 ...
- 【转】Git使用教程之远程仓库
1.远程仓库 在了解之前,先注册github账号,由于你的本地Git仓库和github仓库之间的传输是通过SSH加密的,所以需要一点设置: 第一步:创建SSH Key.在用户主目录下,看看有没有.ss ...
- element-ui的表单验证this.$refs[formName].validate的代码不执行
经过排查,如果自定义验证中,每种情况都要写明确和有回调函数callback var validatePhone = (rule, value, callback) => { const reg ...
- github 分支管理
github 分支管理 最近有同事问我git 如何管理分支,这里我以github为例,做下工作中常用的分支管理操作. 分支管理 作用:假设你准备开发一个新功能,但需要两周才能完成,第一周写了60%,如 ...
- DV型、OV型、EV型证书的主要区别
DV型和OV型证书的区别 DV和OV型证书最大的差别是:DV型证书不包含企业名称信息:而OV型证书包含企业名称信息,以下是两者差别对比表: DV OV 包含企业名称信息 否 是 验证公司名称 ...
- testlink 1.9.19安装
环境平台: 系统:Centos 7.6 数据库:mysql 5.7 PHP版本:PHP 5.6 testlink版本:testlink- 链接:https://pan.baidu.com/s/10Pr ...
- UGUI在两个UI间坐标转换
在UGUI中,在两个Canvas之间进行坐标转换,从CanvasA下的坐标转换到CanvasB下. 或者在同一个界面下,从不同的节点下,转成相同的坐标. 函数定义 public static bool ...
- VS调试
1.调试输出变量值 F9先设置断点,开始调试后,依次选择调试——>窗口——>局部变量和监视——>监视1. 点击“全部中断”——>之后局部变量会显示相关变量值,监视1可以查看变量 ...
- JS高阶---作用域与作用域链
大纲: 主体: (1)概论 (2)层级 执行上下文层级为n+1原则 作用域层级也是n+1原则 验证: (3)函数作用域作用 隔离变量,不同作用域下,相同变量名不会有冲突 (4) .
- 201871010117 石欣钰《面向对象程序设计(Java)》第十二周学习总结
内容 这个作业属于哪个课程 https://www.cnblogs.com/nwnu-daizh/ 这个作业的要求在哪里 https://www.cnblogs.com/nwnu-daizh/p/ ...