1. 程式人生 > >.NET POST提交資料和接收資料 用url傳參方式

.NET POST提交資料和接收資料 用url傳參方式

//1、物件提交,字典方式
        //介面方:public ActionResult GetArry(Car model)
        public void PostResponse()
        {
            HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create("http://demo2.cm-force.com/appapi/apiaccount/aa");
            Encoding encoding = Encoding.UTF8;
            //string param = "UserName=123&UserPwd=123";//post 引數
            Car c = new Car();
            c.Passed = 1;//true
            c.LinkTel = "小測試";
            c.CarBrand = "11111111";
            c.Loads = 101;
            c.UserId = 50;
            c.SortId = 1;
            c.CarArea = "11111111";
            c.CarStateId = 1;
            c.LinkMan = "1111111111";
            c.Sfzh = "141124188789786031";
            c.CarNum = "ABCDE1";
            c.CarLength = 100;
            c.DrivingNum = "11111111";
            c.State = 1;
            c.CarId = 0;
            c.CarOwner = "111111";
            c.CarAreaId = 1;
            c.CarTypeId = 1;
            c.AddTime = DateTime.Now;
            IDictionary<string, string> para = new Dictionary<string, string>();
            para.Add("LinkTel", "第二次測試");
            para.Add("CarBrand", "1111");
            para.Add("Loads", "101");
            para.Add("UserId", "50");
            para.Add("SortId", "1");
            StringBuilder buffer = new StringBuilder();
            int i = 0;
            foreach (string key in para.Keys)
            {
                if (i > 0)
                {
                    buffer.AppendFormat("&{0}={1}", key, para[key]);
                }
                else
                {
                    buffer.AppendFormat("{0}={1}", key, para[key]);
                }
                i++;
            } 
           //JavaScriptSerializer ser = new JavaScriptSerializer();
           //string param = ser.Serialize(c);
            byte[] bs = Encoding.UTF8.GetBytes(buffer.ToString());
            string responseData = String.Empty;
            req.Method = "POST";
            //req.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
            req.ContentLength = bs.Length;


            using (Stream reqStream = req.GetRequestStream())
            {
                reqStream.Write(bs, 0, bs.Length);
                reqStream.Close();
            }
            using (HttpWebResponse response = (HttpWebResponse)req.GetResponse())
            {
                using (StreamReader reader = new StreamReader(response.GetResponseStream(), encoding))
                {
                    responseData = reader.ReadToEnd().ToString();
                }
                Response.Write(responseData);
            }
        }
        //2、連結方式提交資料
        //介面方:public ActionResult GetArry(int UserId,string GroupName)
        //提交引數:string param = "UserId=737&GroupName=一杯美酒";//post 引數
        public void PostMethd()
        {
            HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create("http://demo2.cm-force.com/appapi/apiaccount/GetGroupsByUserId");
            Encoding encoding = Encoding.UTF8;
            string param = "userid=735";//post 引數
            byte[] bs = Encoding.UTF8.GetBytes(param.ToString());
          //byte[] bs = new byte[]{};
            string responseData = String.Empty;
            req.Method = "POST";
            req.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
            req.ContentLength = bs.Length;
            //return;
            using (Stream reqStream = req.GetRequestStream())
            {
                reqStream.Write(bs, 0, bs.Length);
                reqStream.Close();
            }
            using (HttpWebResponse response = (HttpWebResponse)req.GetResponse())
            {
                using (StreamReader reader = new StreamReader(response.GetResponseStream(), encoding))
                {
                    responseData = reader.ReadToEnd().ToString();
                }
                Response.Write(responseData);
            }


        }
        //3、提交陣列
        //介面方:public ActionResult GetArry(string[] arrpost)
        //提交引數:string param = "arrpost=737&arrpost=一杯美酒";//post 引數
        public void PostArrMethd()
        {
            HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create("http://localhost:7242/appapi/apiaccount/GetArry");
            Encoding encoding = Encoding.UTF8;
            string param = "arrpost=737&arrpost=一杯美酒";//post 引數
            byte[] bs = Encoding.UTF8.GetBytes(param.ToString());
            //byte[] bs = new byte[]{};
            string responseData = String.Empty;
            req.Method = "POST";
            req.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
            req.ContentLength = bs.Length;
            //return;
            using (Stream reqStream = req.GetRequestStream())
            {
                reqStream.Write(bs, 0, bs.Length);
                reqStream.Close();
            }
            using (HttpWebResponse response = (HttpWebResponse)req.GetResponse())
            {
                using (StreamReader reader = new StreamReader(response.GetResponseStream(), encoding))
                {
                    responseData = reader.ReadToEnd().ToString();
                }
                Response.Write(responseData);
            }
        }
        //4、提交陣列物件
        //介面方:public ActionResult GetArry(List<Car> arrpost)
        /*  物件
    public class Dasa
    {
        public Dasa() { }
        private string name;
        public string Name
        {
            get { return name; }
            set { name = value; }
        }
        private int age;
        public int Age
        {
            get { return age; }
            set { age = value; }
        }
    }*/
        //提交引數:string param = "arrpost[0].Name=737&arrpost[0].Age=23&arrpost[1].Name=一杯美酒&arrpost[1].Age=25";//post 引數
        public void PostArrObjMethd()
        {
            HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create("http://localhost:7242/appapi/apiaccount/GetArry");
            Encoding encoding = Encoding.UTF8;
            string param = "arrpost[0].Name=737&arrpost[0].Age=23&arrpost[1].Name=一杯美酒&arrpost[1].Age=25";//post 引數
            byte[] bs = Encoding.UTF8.GetBytes(param.ToString());
            //byte[] bs = new byte[]{};
            string responseData = String.Empty;
            req.Method = "POST";
            req.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
            req.ContentLength = bs.Length;
            //return;
            using (Stream reqStream = req.GetRequestStream())
            {
                reqStream.Write(bs, 0, bs.Length);
                reqStream.Close();
            }
            using (HttpWebResponse response = (HttpWebResponse)req.GetResponse())
            {
                using (StreamReader reader = new StreamReader(response.GetResponseStream(), encoding))
                {
                    responseData = reader.ReadToEnd().ToString();
                }
                Response.Write(responseData);
            }
        }
        #region 檔案提交
        
        //上傳呼叫方法
        public void upImg()
        {
            NameValueCollection nvc = new NameValueCollection();
            nvc.Add("id", "TTR");
            nvc.Add("btn-submit-photo", "Upload");
            HttpUploadFile("http://demo2.cm-force.com/appapi/apiaccount/AddtUser", @"D:\1.jpg", "file", "image/jpeg", nvc);
        }
        //5、提交檔案
        public string HttpUploadFile(string url, string file, string paramName, string contentType, NameValueCollection nvc)
        {
            string result = string.Empty;
            string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
            byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
            HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(url);
            wr.ContentType = "multipart/form-data; boundary=" + boundary;
            wr.Method = "POST";
            wr.KeepAlive = true;
            wr.Timeout = 300000;
            wr.Credentials = System.Net.CredentialCache.DefaultCredentials;
            Stream rs = wr.GetRequestStream();
            string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
            foreach (string key in nvc.Keys)
            {
                rs.Write(boundarybytes, 0, boundarybytes.Length);
                string formitem = string.Format(formdataTemplate, key, nvc[key]);
                byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
                rs.Write(formitembytes, 0, formitembytes.Length);
            }
            rs.Write(boundarybytes, 0, boundarybytes.Length);
            string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";
            string header = string.Format(headerTemplate, paramName, file, contentType);
            byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
            rs.Write(headerbytes, 0, headerbytes.Length);
            FileStream fileStream = new FileStream(file, FileMode.Open, FileAccess.Read);
            byte[] buffer = new byte[4096];
            int bytesRead = 0;
            while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
            {
                rs.Write(buffer, 0, bytesRead);
            }
            fileStream.Close();
            byte[] trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
            rs.Write(trailer, 0, trailer.Length);
            rs.Close();
            WebResponse wresp = null;
            try
            {//"路徑:e:\\wwwroot\\wuliu\\wwwroot\\appapi\\apiaccount\\UploadFiles\\D:\\1.jpg"
                //http://stackoverflow.com/questions/566462/upload-files-with-httpwebrequest-multipart-form-data/1924810#1924810
                wresp = wr.GetResponse();
                Stream stream2 = wresp.GetResponseStream();
                StreamReader reader2 = new StreamReader(stream2);
                result = reader2.ReadToEnd();
            }
            catch (Exception ex)
            {
                if (wresp != null)
                {
                    wresp.Close();
                    wresp = null;
                }
            }
            finally
            {
                wr = null;
            }
            return result;
        }
        #endregion
        #endregion