ASP.NET 最全的POST提交数据和接收数据 —— (1) 用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
posted @ 2015-12-05 17:25  平民的麦田  阅读(6829)  评论(0编辑  收藏  举报