• ASP.NET的POST和GET提交并接收处理返回值


    POST方法:

    数据提交

        /// <summary>
        /// POST提交数据接收字符json
        /// </summary>
        /// <param name="url">远程服务器路径</param>
        /// <param name="postData">提交数据</param>
        /// <returns>接收数据</returns>
        public static string PostData(string url, byte[] postData)
        {
            HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(url);
            myRequest.Method = "POST";
            myRequest.ContentType = "application/x-www-form-urlencoded";
            myRequest.ContentLength = postData.Length;
    
            Stream newStream = myRequest.GetRequestStream();
            // Send the data. 
            newStream.Write(postData, 0, postData.Length);
            newStream.Close();
    
            // Get response 
            HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
            StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
            return reader.ReadToEnd();
        }

     注意:POST提交必须有内容提交才可以,否则会报远程服务器返回错误: (411) 所需的长度错误。存在post内容为null的可以修改访问方式为Get

    /// <summary>
            /// POST提交数据接收字符json
            /// </summary>
            /// <param name="url">远程服务器路径</param>
            /// <param name="postData">提交数据</param>
            /// <returns>接收数据</returns>
            public static string PostData(string url, byte[] postData)
            {
                HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(url);
                if (postData != null)
                {
                    myRequest.Method = "POST";
                    // Send the data. 
                    myRequest.ContentType = "application/x-www-form-urlencoded";
                    //myRequest.ContentType = "application/json";//josn格式数据提交
                    myRequest.ContentLength = postData.Length;
                    Stream newStream = myRequest.GetRequestStream();
                    newStream.Write(postData, 0, postData.Length);
                    newStream.Close();
                }
                else
                {
                    myRequest.Method = "GET";//postData无数据时
                }
                // Get response 
                HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
                StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
                return reader.ReadToEnd();
            }

    调用POST提交结果

        public string SendSMS(string mobilenumber,string content)
        {
            string Message = "";
              //远程提交地址
           string RemoteUrl = "http://www.cangcool.com/sms.action?";
           string URL = RemoteUrl;
           string Data = string.Format("u={0}&p={1}&m={2}&c={3}&s={4}&g={5}", _UserName, _Pwd, mobilenumber, content,"","");
            byte[] ByteData=System.Text.Encoding.Default.GetBytes(Data);
            Message = PostData(URL, ByteData);
            //JavaScriptSerializer serializer = new JavaScriptSerializer();
            //jsonOut = serializer.Deserialize<RecordInfo>(strJsonInput);
            return Message;
        }

    直接加载POST无参提交数据

     public ActionResult PayOnline()
           {
               System.IO.Stream sm = Request.InputStream;
               int len = (int)sm.Length;//post数据长度
               byte[] inputByts = new byte[len];//字节数据,用于存储post数据
               sm.Read(inputByts, 0, len);//将post数据写入byte数组中
               sm.Close();//关闭IO流
               string data = Encoding.GetEncoding("UTF-8").GetString(inputByts);//转为UTF-8编码
               data = Server.UrlDecode(data);
               return View(data);
           }

     C#POST提交文件上传

    WebClient webclient = new WebClient();
            byte[] responseArray = webclient.UploadFile("http://localhost:51881/API/Aliyun/UploadBusinessCard?ClientKey=111&UserID=654&File_key=file ", "POST", @"D:1.jpg");
            string getPath = System.Text.Encoding.GetEncoding("UTF-8").GetString(responseArray);

     POST提交参数数据和上传文件

     private static string HttpPostData(string url, int timeOut, string fileKeyName,string fileName, byte[] fileData,Dictionary<string,string> stringDict)
            {
                string responseContent;
                var memStream = new MemoryStream();
                var webRequest = (HttpWebRequest)WebRequest.Create(url);
                // 边界符  
                var boundary = "---------------" + DateTime.Now.Ticks.ToString("x");
                // 边界符  
                var beginBoundary = Encoding.ASCII.GetBytes("--" + boundary + "
    ");
                //var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);//文件路径方式获取文件流
                var fileStream = new MemoryStream(fileData);
                // 最后的结束符  
                var endBoundary = Encoding.ASCII.GetBytes("--" + boundary + "--
    ");
                // 设置属性  
                webRequest.Method = "POST";
                webRequest.Timeout = timeOut;
                webRequest.ContentType = "multipart/form-data; boundary=" + boundary;
                // 写入文件  
                const string filePartHeader =
                    "Content-Disposition: form-data; name="{0}"; filename="{1}"
    " +
                     "Content-Type: application/octet-stream
    
    ";
                var header = string.Format(filePartHeader, fileKeyName, fileName);
                var headerbytes = Encoding.UTF8.GetBytes(header);
                memStream.Write(beginBoundary, 0, beginBoundary.Length);
                memStream.Write(headerbytes, 0, headerbytes.Length);
                var buffer = new byte[1024];
                int bytesRead; // =0  
                while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
                {
                    memStream.Write(buffer, 0, bytesRead);
                }
                // 写入字符串的Key  
                var stringKeyHeader = "
    --" + boundary +
                                       "
    Content-Disposition: form-data; name="{0}"" +
                                       "
    
    {1}
    ";
                foreach (byte[] formitembytes in from string key in stringDict.Keys
                                                 select string.Format(stringKeyHeader, key, stringDict[key])
                                                     into formitem
                                                 select Encoding.UTF8.GetBytes(formitem))
                {
                    memStream.Write(formitembytes, 0, formitembytes.Length);
                }
                // 写入最后的结束边界符  
                memStream.Write(endBoundary, 0, endBoundary.Length);
                webRequest.ContentLength = memStream.Length;
                var requestStream = webRequest.GetRequestStream();
                memStream.Position = 0;
                var tempBuffer = new byte[memStream.Length];
                memStream.Read(tempBuffer, 0, tempBuffer.Length);
                memStream.Close();
                requestStream.Write(tempBuffer, 0, tempBuffer.Length);
                requestStream.Close();
                var httpWebResponse = (HttpWebResponse)webRequest.GetResponse();
                using (var httpStreamReader = new StreamReader(httpWebResponse.GetResponseStream(),
                                                                Encoding.GetEncoding("utf-8")))
                {
                    responseContent = httpStreamReader.ReadToEnd();
                }
                fileStream.Close();
                httpWebResponse.Close();
                webRequest.Abort();
                return responseContent;
            }

     调用方法:

     public void ProcessRequest(HttpContext context)
            {
                context.Response.ContentType = "text/plain";
                var url = "https://fileapi.instrument.com.cn/upflash/upimg.ashx";
    
                string[] filetype = { ".rar", ".doc", ".docx", ".zip", ".pdf", ".txt", ".swf", ".wmv", ".ppt", ".pptx", ".caj", ".jpg", ".jpeg", ".gif", ".rar", ".zip", ".xls", ".xlsx" };    //文件允许格式
    
                //文件大小限制,单位MB,同时在web.config里配置环境默认为100MB
                var uploadFilesSize = IM.Utils.Configuration.AppSettings("UploadFilesSize");
                var size = 100;
                if (!string.IsNullOrEmpty(uploadFilesSize))
                {
                    size = Convert.ToInt32(uploadFilesSize);
                }
                var colname = HttpContext.Current.Request["upuser"];
    
                if (string.IsNullOrEmpty(colname))
                {
                    colname = "attachment";
                }
                var file = context.Request.Files[0];
                byte[] bytes = new byte[file.ContentLength];
                using (BinaryReader reader = new BinaryReader(file.InputStream, Encoding.UTF8))
                {
                    bytes = reader.ReadBytes(file.ContentLength);
                }
                var rel=HttpPostData(url, 1000 * 60 * 3, file.FileName, file.FileName, bytes, new Dictionary<string, string>() { { "colname", colname } });
                HttpContext.Current.Response.Write(rel);
            }
    View Code

    GET方法:

    数据提交

        /// <summary>
        /// GET提交
        /// </summary>
        /// <param name="strUrl">远程服务器路径</param>
        /// <param name="charset">字符编码</param>
        /// <returns></returns>
        public static string GeData(string strUrl, string charset)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(strUrl);
            request.Method = "GET";
            request.Timeout = 60000;
            HttpWebResponse response = request.GetResponse() as HttpWebResponse;
            Stream streamReceive = response.GetResponseStream();
            Encoding encoding = Encoding.Default;
            if (!string.IsNullOrEmpty(charset) && Encoding.GetEncoding(charset) != Encoding.Default)
            {
                encoding = Encoding.GetEncoding(charset);
            }
    
            StreamReader streamReader = new StreamReader(streamReceive, encoding);
            return streamReader.ReadToEnd();
        }

    调用GET提交结果

        public string SendSMS(string mobilenumber, string content)
        {
            string Message = "";
            //远程提交地址
            string RemoteUrl = "http://www.cangcool.com/sms.action?";
            string Data = string.Format("u={0}&p={1}&m={2}&c={3}&s={4}&g={5}", _UserName, _Pwd, mobilenumber, content, "", "");
            string URL = RemoteUrl + Data;
            Message = GeData(URL,"UTF-8");
            return Message;
        }
  • 相关阅读:
    一个Mini的ASP.NET Core框架的实现
    DDD领域驱动设计理论篇
    你准备好了在云中工作吗?
    FFM原理及公式推导
    IOS学习:常用第三方库(GDataXMLNode:xml解析库)
    网络数据的XML解析
    iOS开发之html解析
    iOS解析HTML
    iOS设计模式——MVC(Model-View-Controller)
    iOS设计模式——Category
  • 原文地址:https://www.cnblogs.com/loyung/p/4963943.html
Copyright © 2020-2023  润新知