C#中Post和Get提交

1、Post提交

 private string PostWebRequest(string Url, string paramData, string dataEncode)
        {
            string ret = string.Empty;
            try
            {
                Encoding myEncoding = Encoding.GetEncoding(dataEncode);
                byte[] byteArray = myEncoding.GetBytes(paramData); //转化
                HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(Url);
                webReq.Method = “POST”;
                webReq.ContentType = "application/x-www-form-urlencoded";

                webReq.ContentLength = byteArray.Length;
                Stream newStream = webReq.GetRequestStream();
                newStream.Write(byteArray, 0, byteArray.Length);//写入参数
                newStream.Close();
                HttpWebResponse response = (HttpWebResponse)webReq.GetResponse();
                StreamReader sr = new StreamReader(response.GetResponseStream(), myEncoding);
                ret = sr.ReadToEnd();
                sr.Close();
                response.Close();
            }
            catch (Exception ex)
            {
                WriteFileLog(ex.ToString());
                MessageBox.Show(ex.Message);
            }
            return ret;
        }

2、Get提交

   private string GetWebRequest(string Url, string paramData, string dataEncode)
        {
            string requestString = "";
            try
            {
                string reallyUrl = Url;

                Encoding myEncoding = Encoding.GetEncoding(dataEncode);
                // CookieContainer cookieContainer = new CookieContainer();
                HttpWebRequest request = WebRequest.Create(reallyUrl) as HttpWebRequest;
                //  ServicePointManager.CheckCertificateRevocationList = false;
                request.Method = “GET”;
                //   request.KeepAlive = false;
                //   request.AllowAutoRedirect = true;
                request.ContentType = "application/x-www-form-urlencoded";

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                StreamReader responseStream = new StreamReader(response.GetResponseStream(), myEncoding);
                requestString = responseStream.ReadToEnd();
                response.Close();
                responseStream.Close();
            }
            catch (Exception ex)
            {

                WriteFileLog(ex.ToString());
                MessageBox.Show(ex.Message);
            }

 

posted @ 2015-04-28 18:25  梦锁湘江  阅读(455)  评论(0编辑  收藏  举报