c#POST请求php接口

Posted 韩梦芫

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c#POST请求php接口相关的知识,希望对你有一定的参考价值。

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接口的主要内容,如果未能解决你的问题,请参考以下文章

discuz X3.1 源代码阅读,记录代码片段

php post 请求https接口

php如何通过get方法发送http请求,并且得到返回的参数

php模拟post提交请求,curl调用接口

如何用php向服务器发送post请求

关于java post get请求Demo (请求c#iis接口)