方法:
public static string HttpPostJson(string url, string postStr, int timeOut, string charset) { HttpWebRequest wreq = null; HttpWebResponse res = null; string strRst = ""; #region http web request Encoding ecd = Encoding.GetEncoding(charset); byte[] data = ecd.GetBytes(postStr); wreq = (HttpWebRequest)WebRequest.Create(url); wreq.Timeout = timeOut * 1000; wreq.ReadWriteTimeout = timeOut * 1000; wreq.Method = "POST"; wreq.KeepAlive = false; wreq.ContentType = "application/json;charset=utf-8"; wreq.ServicePoint.Expect100Continue = false; //当服务器恢复正常时,访问已经是200时,这个线程还是返回操作超时 wreq.ContentLength = data.Length; using (Stream putStream = wreq.GetRequestStream()) { putStream.Write(data, 0, data.Length); } res = wreq.GetResponse() as HttpWebResponse; byte[] by = new byte[800]; using (Stream stream = res.GetResponseStream()) { int size = 1024; int read = 0; using (MemoryStream ms = new MemoryStream()) { byte[] buffer = new byte[size]; do { read = stream.Read(buffer, 0, size); ms.Write(buffer, 0, read); } while (read > 0); by = ms.ToArray(); } } strRst = ecd.GetString(by); if (res != null) res.Close(); if (wreq != null) wreq.Abort();//主动释放 #endregion return strRst; }
调用:
textBox2.Text = CommonUtils.MU.HttpPostJson(url,textBox1.Text,30,"UTF-8");
END