RestSharp,在nuget中引用进项目来
这里封装了,常用的接口请求方式,Post,Get,还有file上传,header处理,鉴权等方式
using RestSharp; using System; namespace FinanceApi { public class APIHelper { private readonly string baseUrl = "http://192.168.60.108:8081/"; /// <summary> /// http请求接口 /// </summary> /// <param name="url">地址</param> /// <param name="data">数据,json格式化后的数据</param> /// <param name="method">方法 POST,或者get</param> /// <returns></returns> public string HttpRequest(string url, string data, Method method, string file = null) { try { var client = new RestClient(baseUrl + url); var request = new RestRequest(method); request.RequestFormat = DataFormat.Json; if (file == null) request.AddHeader("Content-Type", "application/json"); else { request.AddHeader("Content-Type", "multipart/form-data"); request.AddHeader("user_id", UserCache.Current_UserId.ToString()); request.AddHeader("username", UserCache.Current_UserName); } request.Timeout = 10000; if (data != null) request.AddParameter("application/json; charset=utf-8", data, ParameterType.RequestBody); if (UserCache.CACHE_UserInfoModel != null) request.AddHeader("authorization", "Bearer " + UserCache.CACHE_UserInfoModel.access_token); if (file != null) request.AddFile("file", file); IRestResponse response = client.Execute(request); var responseContent = response.Content; return responseContent; } catch (Exception ex) { return null; } } } }
文章评论