码迷,mamicode.com
首页 > Windows程序 > 详细

C# 使用RestClient 调用接口

时间:2020-05-23 18:50:20      阅读:476      评论:0      收藏:0      [点我收藏+]

标签:taf   code   nan   serialize   returns   上传   com   form   byte   

最近做项目使用RestClient 向第三方接口推送数据。不废话直接贴代码

        /// <summary>
        /// 获取Token
        /// </summary>
        /// <returns></returns>
        public static async Task<string> GetToken()
        {
            var url = $"http://127.0.0.1/terminal-tenant/sys/login";
            var client = new RestClient(url);
            var request = new RestRequest(Method.POST);
            request.RequestFormat = DataFormat.Json;
            var body = new { username = "xxx", password = "xxx" };
            request.AddParameter("application/json; charset=utf-8", JsonConvert.SerializeObject(body), ParameterType.RequestBody);
            IRestResponse response = client.Execute(request);
            var responseContent = response.Content;
            return responseContent;
        }
        /// <summary>
        /// 保存数据
        /// </summary>
        /// <returns></returns>
        public async Task<string> Save(Model model, string token)
        {
            var url = $"http://127.0.0.1/terminal-tenant/app/visitor/save";
            var client = new RestClient(url);
            var request = new RestRequest(Method.POST);
            request.RequestFormat = DataFormat.Json;
            request.AddHeader("token", token);
            request.AddParameter("application/json; charset=utf-8", JsonConvert.SerializeObject(model), ParameterType.RequestBody);
            IRestResponse response = client.Execute(request);
            var responseContent = response.Content;
            return responseContent;
        }
        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="bt"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        public async Task<string> Upload(byte[] bt, string token)
        {
            var url = $"http://127.0.0.1/terminal-tenant/tenant/common/upload";
            var client = new RestClient(url);
            var request = new RestRequest(Method.POST);
            request.RequestFormat = DataFormat.Json;
            request.AddHeader("token", token);
            request.AddFile("file", bt, "multipart/form-data");
            IRestResponse response = client.Execute(request);
            var responseContent = response.Content;
            return responseContent;
        }

 博客文章可以转载,但不可以声明为原创.

C# 使用RestClient 调用接口

标签:taf   code   nan   serialize   returns   上传   com   form   byte   

原文地址:https://www.cnblogs.com/zhangxiaofa/p/12943620.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!