朋友对接酷家乐接口,帮忙简单写的一个测试的请求接口通用类。
代码如下:
//时间戳 public static long timeStamp = 0L; //账号信息 public const string appKey = "appKey"; public const string Appuid = "Appuid "; public const string appSecret = "appSecret "; public static string sign = string.Empty; //post通用方法 public static string Post(string url, string requestBody) { try { if (string.IsNullOrEmpty(url)) { return "地址异常,请检查!"; } timeStamp = GetTimeStamp(); //md5加密 string sign = (appSecret + appKey + timeStamp).MDString(); StringBuilder apiBuilder = new StringBuilder(); apiBuilder.Append(url) // 鉴权的参数作为URL Query Param .Append("?appkey=").Append(appKey) .Append("×tamp=").Append(timeStamp) .Append("&sign=").Append(sign); var client = new RestClient(apiBuilder.ToString()); client.Timeout = -1; var request = new RestRequest(Method.POST); request.AddHeader("Content-Type", "application/json"); request.AddParameter("application/json", requestBody, ParameterType.RequestBody); IRestResponse response = client.Execute(request); return response.Content; } catch (Exception ex) { return ex.Message; } } //get通用方法 public static string Get(string url, string requestBody) { try { if (string.IsNullOrEmpty(url)) { return "接口地址不能为空!"; } timeStamp = GetTimeStamp(); //md5加密 string sign = (appSecret + appKey + timeStamp).MDString(); StringBuilder apiBuilder = new StringBuilder(); apiBuilder.Append(url) // 鉴权的参数作为URL Query Param .Append("?appkey=").Append(appKey) .Append("×tamp=").Append(timeStamp) .Append("&sign=").Append(sign); var client = new RestClient(apiBuilder.ToString()); client.Timeout = -1; var request = new RestRequest(Method.GET); request.AddHeader("Content-Type", "application/json"); request.AddParameter("application/json", requestBody, ParameterType.RequestBody); IRestResponse response = client.Execute(request); return response.Content; } catch (Exception ex) { return ex.Message; } } //获取时间戳 public static long GetTimeStamp() { TimeSpan ts = DateTime.Now - new DateTime(1970, 1, 1, 0, 0, 0, 0); return Convert.ToInt64(ts.TotalMilliseconds); } }
需要引用两个类库:
1、RestSharp
2、Masuit.Tools.Core
账号和密码都需要企业注册,仅供参考使用。