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; }