c# RestSharp(http请求)

介绍: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 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<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

  • 3
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值