1. 程式人生 > 其它 >C# Post請求方法

C# Post請求方法

//1測試有效
public
static string HttpPost(string sim_uid, string mobile, string msg) { string _url = string.Format("需要請求的url"); //json引數 string jsonParam = Newtonsoft.Json.JsonConvert.SerializeObject(new { uid = sim_uid,//使用者openid mobile = mobile, msg
= msg }); var request = (HttpWebRequest)WebRequest.Create(_url); request.Method = "POST"; request.ContentType = "application/json;charset=UTF-8";//ContentType byte[] byteData = Encoding.UTF8.GetBytes(jsonParam); int length = byteData.Length; request.ContentLength
= length; Stream writer = request.GetRequestStream(); writer.Write(byteData, 0, length); writer.Close(); var response = (HttpWebResponse)request.GetResponse(); var responseString = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("
utf-8")).ReadToEnd(); return responseString.ToString(); }
        //2post(未測試)
     public static string PostReqiest(string url, Dictionary<string, string> dic) { string result = ""; ServicePointManager.Expect100Continue = true; ServicePointManager.CheckCertificateRevocationList = true; ServicePointManager.DefaultConnectionLimit = 100; ServicePointManager.SecurityProtocol = (SecurityProtocolType)(0xc0 | 0x300 | 0xc00); ServicePointManager.ServerCertificateValidationCallback = delegate { return true; }; HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url); req.ProtocolVersion = HttpVersion.Version10; req.KeepAlive = false; req.Method = "POST"; req.ContentType = "application/json"; #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()); req.ContentLength = data.Length; using (Stream reqStream = req.GetRequestStream()) { reqStream.Write(data, 0, data.Length); reqStream.Close(); } #endregion HttpWebResponse resp = (HttpWebResponse)req.GetResponse(); Stream stream = resp.GetResponseStream(); //獲取響應內容 using (StreamReader reader = new StreamReader(stream, Encoding.UTF8)) { result = reader.ReadToEnd(); } return result; }