介绍:RestSharp

RestSharp是一个轻量的,不依赖任何第三方的模拟Http的组件或者类库。RestSharp具体以下特性;支持net4.0++,支持HTTP的GET, POST, PUT, HEAD, OPTIONS, DELETE等操作,支持oAuth 1, oAuth 2, Basic, NTLM and Parameter-based Authenticators等授权验证等。截止当前目前是github最高stars的http类库。

  官方文档:https://restsharp.dev/get-help/
  github:https://github.com/restsharp/RestSharp

nuget安装:

准备Webapi接口:

public class UnityController : ApiController{private IUserService _userService = null;public UnityController(IUserService userService){_userService = userService;}// GET api/<controller>public IEnumerable<Student> Get(){//return UnityFactoryUtil.GetServer<IUserService>().GetList();return _userService.GetList();}// POST api/<controller>public string Post([FromBody]string value){return value;}[Route("PostTest")]public string PostTest([FromBody]Student stu){return Newtonsoft.Json.JsonConvert.SerializeObject(stu);}}public class FirstController : ApiController{// GET api/<controller>public IEnumerable<string> Get(){return new string[] { "value1", "value2" };}// GET api/<controller>/5[AllowAnonymous]//不使用验证public string Get(int id){return "value";}[AllowAnonymous]//不使用验证[Route("GetById")]public string GetById([FromUri] Student stu){return "value";}}[RoutePrefix("api/File")]public class FileController : ApiController{/// 上传文件/// </summary>/// <returns></returns>[HttpPost]public string UploadFiles(){string result = "";var path=System.Web.Hosting.HostingEnvironment.MapPath("~/Upload");HttpFileCollection files = HttpContext.Current.Request.Files;if (files != null && files.Count > 0){for (int i = 0; i < files.Count; i++){HttpPostedFile file = files[i];string filename = file.FileName;string FileName = Guid.NewGuid().ToString()+Path.GetExtension(filename); ;string FilePath = path+"\\" + DateTime.Now.ToString("yyyy-MM-dd") + "\\";DirectoryInfo di = new DirectoryInfo(FilePath);if (!di.Exists){di.Create();}try{file.SaveAs(FilePath + FileName);result ="上传成功";}catch (Exception ex){result = "上传文件写入失败:" + ex.Message;}}}else{result = "上传的文件信息不存在!";}return result;}/// <summary>/// 下载文件/// </summary>[HttpGet]public HttpResponseMessage DownloadFile(){string fileName = "image.jpg";string filePath = HttpContext.Current.Server.MapPath("~/Upload/") + "image.jpg";FileStream stream = new FileStream(filePath, FileMode.Open);HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);response.Content = new StreamContent(stream);response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment"){FileName = HttpUtility.UrlEncode(fileName)};response.Headers.Add("Access-Control-Expose-Headers", "FileName");response.Headers.Add("FileName", HttpUtility.UrlEncode(fileName));return response;}}

使用介绍:

环境:net4.0、RestSharp(105.2.3.0版本)

注意bug:var response=client.Execute<Student>(request); 该方法序列化成实体有问题,可以改成序列化成dynamic(动态类)

           //Get{var client = new RestClient("https://localhost:44370/api/First");client.Authenticator = new RestSharp.Authenticators.HttpBasicAuthenticator("admin", "admin");var request = new RestRequest(Method.GET);request.AddHeader("Content-Type", "application/json");request.Timeout = 10000;request.AddHeader("Cache-Control", "no-cache");  request.AddParameter("name", "value"); // adds to POST or URL querystring based on Methodrequest.AddUrlSegment("id", "123"); // replaces matching token in request.Resource// add parameters for all properties on an object//request.AddJsonObject(@object);//直接传输一个实体//request.AddJsonBody("实体");//request.AddObject(object, "PersonId", "Name", ...);request.AddHeader("header", "value");//add files to upload (works with compatible verbs)//request.AddFile("file", path);var response = client.Execute(request);var content = response.Content;}//POST(单个参数与){var client = new RestClient("https://localhost:44370/api/Unity");var request = new RestRequest(Method.POST);request.AddParameter("", "value");var response = client.Execute(request);var content = response.Content;}//POST(实体参数){var client = new RestClient("https://localhost:44370/api/Unity/PostTest");var request = new RestRequest(Method.POST);request.AddHeader("Content-Type", "application/json");Student stu = new Student{AGE = 26,ID = 1,NAME = "czk",PWD = 123456};request.AddJsonBody(stu);//var response = client.Execute<Student>(request);//报错、var response = client.Execute<dynamic>(request);var retStu = Newtonsoft.Json.JsonConvert.DeserializeObject<Student>(response.Data);}//上传文件{var client = new RestClient("https://localhost:44370/api/File/UploadFiles");var request = new RestRequest(Method.POST);var imagePath = AppDomain.CurrentDomain.BaseDirectory + @"File\image.jpg";request.AddFile("image", imagePath);var response = client.Execute(request);var content = response.Content;}//下载文件{var client = new RestClient("https://localhost:44370/api/File/DownloadFile");var request = new RestRequest(Method.GET);string tempFile = Path.GetTempFileName();var writer = File.OpenWrite(tempFile);request.ResponseWriter = responseStream =>{using (responseStream){responseStream.CopyTo(writer);}};byte[] bytes = client.DownloadData(request);}

扩展:

c# EasyHttp (http请求库):https://blog.csdn.net/czjnoe/article/details/106483861

demo:https://github.com/czjnoe/GitHubDemo/tree/master/RestSharpDemo

github下载慢参考:https://blog.csdn.net/czjnoe/article/details/106321174

请使用手机"扫一扫"x

c# RestSharp(http请求)相关推荐

  1. .net core实践系列之短信服务-Api的SDK的实现与测试

    前言 上一篇<.net core实践系列之短信服务-Sikiro.SMS.Api服务的实现>讲解了API的设计与实现,本篇主要讲解编写接口的SDK编写还有API的测试. 或许有些人会认为, ...

  2. C# 使用RestSharp实现Postman中的各种形式的请求

    目录 一.导入命名空间 二.构建客户端 ◆ 创建客户端对象 ◆ 设置当前URL ◆ 设置响应超时 ◆ 添加默认Header ◆ 添加单项Cookie ◆ 添加多项Cookie 三.构建请求 ◆ 创建请 ...

  3. .Net(C#)后台发送Get和Post请求(HttpClient、Flurl.Http、WebRequest和WebClient、RestSharp)

    本文主要介绍分别通过HttpClient.Flurl.Http.WebRequest和WebClient.RestSharp发送Get和Post请求的方法. 原文地址:https://www.cjav ...

  4. c# RestSharp 发送 x-www-form-urlundecoded 请求

    今天发请求发现失败了,找了一圈全是错误得答案,不追究是不是因为版本问题,自己通过不断改参数试出来了,可以发送成功得写法.做个小笔记. 后面的类型不要使用 requestBody,不然参数会跑到Body ...

  5. .Net Core下发送WebRequest请求的两种方式

    1.使用RestSharp.NetCore 2.使用WebApi请求方式 转载于:https://www.cnblogs.com/mailaidedt/p/6525501.html

  6. 服务端发post请求产生的编码问题

    最近在做一个功能,大概功能是这样的,供应商提供http接口给我们,然后我们抓取供应商的数据保存到数据库,问题在于他们编码格式是gb2312的,而我们是utf-8. 大家可能会有个误区,post请求是无 ...

  7. java restsharp_C# RestSharp应用

    C# RestSharp应用 开通博客是想将自己所学的东西记录下来,以便自己查缺补漏,希望自己能坚持下去 正题关于RestSharp的使用 下载 NuGet直接搜索即可,最新版本RestSharp需要 ...

  8. xamarin android网络请求总结

    xamarin android中网络请求的框架非常多,在项目中使用的是第三方的一个网络请求框架restsharp,应该是github上.net网络请求最多star的框架,没有之一.这里就简单汇总了其他 ...

  9. RestSharp with polly 封装

    BaseRequest public class BaseRequest {public int TimeOut { get; set; } = 300;public Method Method { ...

  10. WMS中RestSharp的使用

    RestSharp 简介 官方:RestSharp 可能是.NET 最流行的 HTTP 客户端库.它具有自动序列化和反序列化.请求和响应类型检测.多种身份验证和其他有用功能,正被数十万个项目使用. R ...

最新文章

  1. python种r b u f作用
  2. encoder-decoder 注意力机制整理名望所
  3. python提取图像的每一帧
  4. Facebook推开源软件平台ParlAI,能否解决机器人灵魂缺失问题?
  5. [JLOI 2012]树
  6. CodeForces - 1305D Kuroni and the Celebration(思维,互动题)
  7. 提高软件开发、软件维护的效率和质量的利器
  8. Flask中的HttpResponse Redirect 和Render
  9. CGAffineTransformMakeRotation 实现旋转
  10. TIBCO Spotfire 入门指南
  11. 能否将一个网址(如QQ空间网址),打包成APK,然后别人下载APK安装到手机后,点击进入这个网址?
  12. 微信公众平台入门到精通-新浪云计算平台注册和使用
  13. 个人或小微企业网络从IPv4升级到IPv6/v4硬件配置及注意事项
  14. 如何让谷歌收录自己的网站?谷歌多久收录我的网站?
  15. js中数组的高逼格操作(filter、sort、map、reduce)
  16. 【网络安全】登录问题(一)Session/Cookie源码分析
  17. 【通知】关于SRRC认证无线电发射设备型号核准的通知
  18. 北京理工计算机学院夏令营机试,北京理工大学计算机近几年机试真题及题解 上...
  19. FPGA Verilog AD7606驱动代码,包含SPI模式读取和并行模式读取两种
  20. info()函数与describe函数

热门文章

  1. 教你实战Flutter Deskstop之Tinypng(熊猫图片压缩)GUI工具
  2. python破解百度网盘提取码_Python 一键获取百度网盘提取码
  3. php怎么自动识别车牌号,车牌号自动识别系统怎么录入,很多你不知道的潜规则...
  4. CoppeliaSim(Vrep)动力学仿真入门设置
  5. 通达信 移动平均算法_中山证券通达信下载-中山证券通达信软件 v1.06 官方版
  6. a59s刷机包卡刷 oppo_OPPO A59S刷机包下载|OPPO A59S刷机包官方下载-太平洋下载中心...
  7. 互动媒体技术专题2——多视角认识十二个“一” 技术预演与方案设计
  8. intptr java_intptr_t 其实不是指针类型 (转载)
  9. 最新版本的000-919题库
  10. 怎样用等价类划分设计测试用例