码迷,mamicode.com
首页 > Windows程序 > 详细

c#POST请求php接口

时间:2018-01-03 15:54:38      阅读:279      评论:0      收藏:0      [点我收藏+]

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

POST请求php接口

/// <summary>  
        /// 指定Post地址使用Get 方式获取全部字符串  
        /// </summary>  
        /// <param name="url">请求后台地址</param>  
        /// <returns></returns>  
        public string Post(string url, SortedDictionary<string, 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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!