c#POST请求php接口

2021-07-16 15:19

阅读:662

标签:tle   str   turn   c#   mat   timestamp   append   获取   code   

POST请求php接口

///   
        /// 指定Post地址使用Get 方式获取全部字符串  
        ///   
        /// 请求后台地址  
        ///   
        public string Post(string url, SortedDictionarystring, object> dic)
        {
            string result = "";
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            //签名加密
            string sign = sh.MakeSign(dic);
            request.Headers.Add("sign", sign);
            request.Headers.Add("apptype", "winform");
            request.Headers.Add("sendtime", GetTimeStamp());

            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.Accept = "*/*";

            #region 添加Post 参数  
            StringBuilder builder = new StringBuilder();
            int i = 0;
            foreach (var item in dic)
            {
                if (i > 0)
                    builder.Append("&");
                builder.AppendFormat("{0}={1}", item.Key, item.Value);
                i++;
            }
            byte[] data = Encoding.UTF8.GetBytes(builder.ToString());
            request.ContentLength = data.Length;
            using (Stream reqStream = request.GetRequestStream())
            {
                reqStream.Write(data, 0, data.Length);
                reqStream.Close();
            }
            #endregion
            HttpWebResponse resp;
            try
            {
                 resp = (HttpWebResponse)request.GetResponse();

            }
            catch (WebException ex)
            {
                 resp =(HttpWebResponse)ex.Response;
            }
            Stream stream = resp.GetResponseStream();
            //获取响应内容  
            using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
            {
                result = reader.ReadToEnd();
            }

            return result;
        }

 

c#POST请求php接口

标签:tle   str   turn   c#   mat   timestamp   append   获取   code   

原文地址:https://www.cnblogs.com/siyunianhua/p/8183616.html


评论


亲,登录后才可以留言!