• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C#模拟Form提交

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

转:忘了.....

提交核心部分

/// <summary>  
        /// 使用Post方法获取字符串结果  
        /// </summary>  
        /// <param name="url"></param>  
        /// <param name="formItems">Post表单内容</param>  
        /// <param name="cookieContainer"></param>  
        /// <param name="timeOut">默认20秒</param>  
        /// <param name="encoding">响应内容的编码类型(默认utf-8)</param>  
        /// <returns></returns>  
        public static ResultData PostForm(string url, List<FormItemModel> formItems, CookieContainer cookieContainer = null, string refererUrl = null, Encoding encoding = null, int timeOut = 20000)
        {
            //try
            //{
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            #region 初始化请求对象  
            request.Method = "POST";
            request.Timeout = timeOut;
            request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
            request.KeepAlive = true;
            request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36";
            if (!string.IsNullOrEmpty(refererUrl))
                request.Referer = refererUrl;
            if (cookieContainer != null)
                request.CookieContainer = cookieContainer;
            #endregion

            string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");//分隔符  
            request.ContentType = string.Format("multipart/form-data; boundary={0}", boundary);
            //请求流  
            var postStream = new MemoryStream();
            #region 处理Form表单请求内容  
            //是否用Form上传文件  
            var formUploadFile = formItems != null && formItems.Count > 0;
            if (formUploadFile)
            {
                //文件数据模板  
                string fileFormdataTemplate = "--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"" + "\r\nContent-Type: \"{2}\"" + "\r\n\r\n";
                //图片数据模板
                string picFormdataTemplate = "--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\";filename=\"{1}\"\r\nContent-Type:\"{2}\"\r\n\r\n";
                //文本数据模板  
                string dataFormdataTemplate = "--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}\r\n";
                foreach (var item in formItems)
                {
                    string formdata = null;
                    switch (item.formItemType)
                    {
                        case FormitemTypeEnum.文件:
                            //上传文件  
                            formdata = string.Format(
                                fileFormdataTemplate,
                                item.Key, //表单键  
                                item.FileName,
                                item.Value);
                            break;
                        case FormitemTypeEnum.图片:
                            //上传图片
                            formdata = string.Format(
                                picFormdataTemplate,
                                item.Key, //表单键 
                                item.FileName,
                                item.Value);
                            break;
                        case FormitemTypeEnum.文本:
                        default:
                            //上传文本  
                            formdata = string.Format(
                                dataFormdataTemplate,
                                item.Key,
                                item.Value);
                            break;
                    }

                    //统一处理  
                    byte[] formdataBytes = null;
                    //第一行不需要换行  
                    //if (postStream.Length == 0)
                    //    formdataBytes = Encoding.UTF8.GetBytes(formdata.Substring(2, formdata.Length - 2));
                    //else
                        formdataBytes = Encoding.UTF8.GetBytes(formdata);
                    postStream.Write(formdataBytes, 0, formdataBytes.Length);

                    //写入文件内容  
                    if (item.FileContent != null && item.FileContent.Length > 0)
                    {
                        using (var stream = item.FileContent)
                        {
                            byte[] buffer = new byte[1024];
                            int bytesRead = 0;
                            while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) != 0)
                            {
                                postStream.Write(buffer, 0, bytesRead);
                            }
                        }
                        byte[] imgbyteend = Encoding.UTF8.GetBytes("\r\n");
                        postStream.Write(imgbyteend, 0, imgbyteend.Length);
                    }
                }
                //结尾  
                var footer = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");
                postStream.Write(footer, 0, footer.Length);

            }
            else
            {
                request.ContentType = "application/x-www-form-urlencoded";
            }
            #endregion

            request.ContentLength = postStream.Length;

            #region 输入二进制流  
            if (postStream != null)
            {
                postStream.Position = 0;
                //直接写入流  
                Stream requestStream = request.GetRequestStream();

                byte[] buffer = new byte[1024];
                int bytesRead = 0;
                while ((bytesRead = postStream.Read(buffer, 0, buffer.Length)) != 0)
                {
                    requestStream.Write(buffer, 0, bytesRead);
                }

                ////debug
                //postStream.Seek(0, SeekOrigin.Begin);
                //StreamReader sr = new StreamReader(postStream);
                //var postStr = sr.ReadToEnd();
                postStream.Close();//关闭文件访问
            }
            #endregion

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            if (cookieContainer != null)
            {
                response.Cookies = cookieContainer.GetCookies(response.ResponseUri);
            }

            using (Stream responseStream = response.GetResponseStream())
            {
                using (StreamReader myStreamReader = new StreamReader(responseStream, encoding ?? Encoding.UTF8))
                {
                    string retString = myStreamReader.ReadToEnd();
                    ZY_MicronewsResult mresult = JsonConvert.DeserializeObject<ZY_MicronewsResult>(retString);
                    if (!string.IsNullOrEmpty(mresult.response))
                    {
                        return ResultData.Access();
                    }
                    else
                    {
                        return ResultData.Fail(mresult.error);
                    }
                }
            }
            //}
            //catch (Exception ex)
            //{
            //    return ResultData.Fail(ex.Message);
            //}
        }

 //实体类

/// <summary>  
        /// 表单数据项  
        /// </summary>  
        public class FormItemModel
        {
            public FormitemTypeEnum formItemType { get; set; } = FormitemTypeEnum.文本;
            /// <summary>  
            /// 表单键,request["key"]  
            /// </summary>  
            public string Key { set; get; }
            /// <summary>  
            /// 表单值,上传文件时忽略,request["key"].value
            /// 格式:application/octet-stream
            /// </summary>  
            public string Value { set; get; }
            public byte[] pic_bytes { get; set; }
            /// <summary>  
            /// 是否是文件  
            /// </summary>  
            public bool IsFile
            {
                get
                {
                    if (FileContent == null || FileContent.Length == 0)
                        return false;

                    if (FileContent != null && FileContent.Length > 0 && string.IsNullOrWhiteSpace(FileName))
                        throw new Exception("上传文件时 FileName 属性值不能为空");
                    return true;
                }
            }
            /// <summary>  
            /// 上传的文件名  
            /// </summary>  
            public string FileName { set; get; }
            /// <summary>  
            /// 上传的文件内容  
            /// </summary>  
            public Stream FileContent { set; get; }
            /// <summary>
            /// 获取上传文件Model
            /// </summary>
            /// <param name="key">名称</param>
            /// <param name="value">内容</param>
            /// <returns></returns>
            public static FormItemModel GetTextModel(string key, string value)
            {
                var model = new Model.Common.FormItemModel
                {
                    Key = key,
                    Value = value,
                    formItemType = Model.Common.FormitemTypeEnum.文本
                };
                return model;
            }
            /// <summary>
            /// 获取上传文件Model
            /// </summary>
            /// <param name="url">url路径</param>
            /// <returns></returns>
            public static FormItemModel GetFileModel(string url)
            {
                Uri uri = null;
                try
                {
                    uri = new Uri(url);
                }
                catch
                {
                    return null;
                }
                var bit = Model.Common.DownloadImg(uri.AbsoluteUri);
                System.IO.MemoryStream memo = new System.IO.MemoryStream();
                bit.Save(memo, System.Drawing.Imaging.ImageFormat.Jpeg);
                memo.Position = 0;
                var model = new Model.Common.FormItemModel
                {
                    Key = "file",
                    Value = "application/octet-stream",
                    FileName = Path.GetFileName(uri.AbsoluteUri),
                    formItemType = Model.Common.FormitemTypeEnum.文件,
                    FileContent = memo
                };
                return model;
            }
            /// <summary>
            /// 获取上传图片Model
            /// </summary>
            /// <param name="url">url路径</param>
            /// <returns></returns>
            public static FormItemModel GetImgModel(string key, string url)
            {
                Uri uri = null;
                try
                {
                    uri = new Uri(url);
                }
                catch
                {
                    return null;
                }
                var bit = Model.Common.DownloadImg(uri.AbsoluteUri);
                System.IO.MemoryStream memo = new System.IO.MemoryStream();
                bit.Save(memo, System.Drawing.Imaging.ImageFormat.Jpeg);
                memo.Position = 0;
                var model = new Model.Common.FormItemModel
                {
                    Key = key,
                    Value = "application/octet-stream",
                    FileName = Path.GetFileName(uri.AbsoluteUri),
                    formItemType = Model.Common.FormitemTypeEnum.图片,
                    FileContent = memo
                };
                return model;
            }
            /// <summary>
            /// 获取上传图片Model
            /// </summary>
            /// <param name="key">名称</param>
            /// <param name="fileName">文件名</param>
            /// <param name="stream">文件流</param>
            /// <returns></returns>
            public static FormItemModel GetImgModel(string key, string fileName, Stream stream)
            {
                stream.Position = 0;
                var model = new Model.Common.FormItemModel
                {
                    Key = key,
                    Value = "application/octet-stream",
                    FileName = fileName,
                    formItemType = Model.Common.FormitemTypeEnum.图片,
                    FileContent = stream
                };
                return model;
            }
        }
        /// <summary>
        /// Form上传类型
        /// </summary>
        public enum FormitemTypeEnum
        {
            文本 = 0,
            文件 = 1,
            图片 = 2
        }

 调用实例

string url = "http://xxxxx.com";
            List<Model.Common.FormItemModel> formItems = new List<Model.Common.FormItemModel>();
            formItems.Add(Model.Common.FormItemModel.GetTextModel("visible", "-1"));  //文本参数
            var imgs = model_MicroNews.MicroNews_imgurl.ToList();
            for (int i = 0; i < imgs.Count; i++)
            {
                var img = imgs[i];
                formItems.Add(Model.Common.FormItemModel.GetImgModel("pic_" + (i + 1), "pic_" + (i + 1) + ".jpeg", img.stream));  //图片
            }

            var result = Model.Common.PostForm(url, formItems);

 


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
传奇3外挂加密解密过程(C#)版发布时间:2022-07-10
下一篇:
c#开发Mongo笔记第七篇发布时间:2022-07-10
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap