C# Post 接口请求样例

很久没有写接口了,正好今天写到了接口,记录一下

封装Http Post请求,这里的请求头是 request.ContentType = “application/json”; 复制后根据实际去修改,不要生搬硬套搞拿来主义:

        /// 
        /// 发送http请求,
        /// 
        /// 
        /// 
        /// 
        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();
            phoneList.Add("152*******73");
            phoneList.Add("155*******03");
            var jsPhone = JsonConvert.SerializeObject(phoneList);
            Dictionary dic = new Dictionary();
            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.***********/batchSendMessage", json));
            var result = JsonConvert.DeserializeObject(res);
            return Json(result);
        }

接口返回内容:
在这里插入图片描述

ok,搞定。

你可能感兴趣的:(MVC,c#)