c# RestSharp(http请求)

您所在的位置:网站首页 framework451安装失败 c# RestSharp(http请求)

c# RestSharp(http请求)

2024-01-24 22:46| 来源: 网络整理| 查看: 265

介绍: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/ public IEnumerable Get() { //return UnityFactoryUtil.GetServer().GetList(); return _userService.GetList(); } // POST api/ 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/ public IEnumerable Get() { return new string[] { "value1", "value2" }; } // GET api//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 { /// 上传文件 /// /// [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; } /// /// 下载文件 /// [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(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 Method request.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(request);//报错、 var response = client.Execute(request); var retStu = Newtonsoft.Json.JsonConvert.DeserializeObject(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



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3