Nuget安装RestSharp版本,不同版本之间的区别有很大,当前这个写法基于以下版本
public class APIHelper{private readonly string baseUrl = ConfigurationManager.AppSettings["connectionString"].ToString(); /// <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", System.Web.HttpUtility.UrlEncode(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;}}}
接口调用