很久没有写接口了,正好今天写到了接口,记录一下
封装Http Post请求,这里的请求头是 request.ContentType = “application/json”; 复制后根据实际去修改,不要生搬硬套搞拿来主义:
/// <summary>/// 发送http请求,/// </summary>/// <param name="url"></param>/// <param name="jsonParam"></param>/// <returns></returns>public static HttpWebResponse CreatePostHttpResponse(string url, string jsonParam){HttpWebRequest request = null;request = WebRequest.Create(url) as HttpWebRequest;request.Proxy = null;request.Method = "POST";request.ContentType = "application/json";byte[] data = Encoding.UTF8.GetBytes(jsonParam);request.ContentLength = data.Length;using (Stream stream = request.GetRequestStream()){stream.Write(data, 0, data.Length);}return request.GetResponse() as HttpWebResponse;}
封装获取请求的数据的方法
public static string GetResponseString(HttpWebResponse webresponse){using (Stream s = webresponse.GetResponseStream()){StreamReader reader = new StreamReader(s, Encoding.UTF8);return reader.ReadToEnd();}}
封装反序列化时需要用到的class:
public class TextMsg {public int resultCode { get; set; }public string resultMsg { get; set; }public string resultMap { get; set; }}
准备工作都做好了,实现接口吧
public IActionResult Text() {var time = DateTime.Now.ToString("yyyyMMddHHmmss");//MD5加密var sign =GetMD5_Utf8("nqk6E4LP********e5Qm" + time + "Kyw****NrU");var phoneList = new List<string>();phoneList.Add("152*******73");phoneList.Add("155*******03");var jsPhone = JsonConvert.SerializeObject(phoneList);Dictionary<string, object> dic = new Dictionary<string, object>();dic.Add("applicationId", "nqk****Rb");dic.Add("password", "i7****Qm");dic.Add("requestTime", time);dic.Add("sign", sign);dic.Add("funCode", "1002");dic.Add("mobiles", phoneList);dic.Add("content", "你好");//序列化var json = JsonConvert.SerializeObject(dic);var res = GetResponseString(CreatePostHttpResponse("http://api.eyun.openmas.net/yunmas_api/smsApi/batchSendMessage", json));var result = JsonConvert.DeserializeObject<TextMsg>(res);return Json(result);}
接口返回内容:
ok,搞定。