httpwebrequest模拟请求奇怪错误

小道消息 2014-11-27 08:10:06
httpwebrequest模拟请求 模拟请求表单的post请求 表单时 multipart/form-data模式的模拟请求出错
错误信息如下



Specified value has invalid Control characters.
Parameter name: value
at System.Net.WebHeaderCollection.CheckBadChars(String name, Boolean isHeaderValue)
at System.Net.HttpWebRequest.SetSpecialHeaders(String HeaderName, String value)
at System.Net.HttpWebRequest.set_Referer(String value)
at SdStateGridAcquirer.HTMLHelper.HttpPostS(String url, String postdata, String referer, String boundary)
...全文
568 11 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
11 条回复
切换为时间正序
请发表友善的回复…
发表回复
小道消息 2014-11-29
  • 打赏
  • 举报
回复
这是部分代码
 string boundary =DateTime.Now.Ticks.ToString("x");
这是我生成的 boundary 是不是跟网站上的不一样导致的
小道消息 2014-11-29
  • 打赏
  • 举报
回复
 public static bool HttpPostS(string url, string postdata, string referer, string boundary)
        {
            bool st = true;
            try
            {
                string result = "";
                CookieContainer cCurrent = new CookieContainer();
                Uri u = new Uri(url);
                cCurrent.Add(u, new Cookie("JSESSIONID", jsessionId));
                cCurrent.Add(u, new Cookie("logonUsername", XF_Main.UserName));
                //if (P3p != null)
                //{
                //    cCurrent.Add(u, new Cookie("P3P", P3p));
                //}                       
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

                var memStream = new MemoryStream();
                // 边界符
                var beginBoundary = Encoding.ASCII.GetBytes("--" + "---------------------------" + boundary + "\r\n");
                var fileStream = new FileStream(Application.StartupPath+@"\file.dat", FileMode.Open, FileAccess.Read);
                // 最后的结束符
                var endBoundary = Encoding.ASCII.GetBytes("--" + "---------------------------" + boundary + "--\r\n");
                
                //设置属性
                request.Headers.Clear();
                request.Method = "POST";//必须为大写,不然会出错   
                //request.Headers.Add("headName", HttpUtility.UrlEncode("value"));
                request.ContentType = "multipart/form-data; boundary=---------------------------" + boundary;//
                request.Accept = "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/msword, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/xaml+xml, application/x-ms-xbap, application/x-ms-application, */*";
                request.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 2.0.50727; .NET4.0C; .NET4.0E)";

                XF_Main.WriteErrorLog(referer);
                //new NameValueCollection()
                //request.ContentLength = data.Length;
                request.Referer = referer;
                request.AllowAutoRedirect = true;
                request.KeepAlive = true;
                request.CookieContainer = cCurrent;
                request.Timeout = 6000;    //超时时间            
                XF_Main.WriteErrorLog("3");
                //写入上传文件
                string filePartHeader = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n" + "Content-Type: text/plain\r\n\r\n";
                var header = string.Format(filePartHeader, "wkstAttach.contentFile", Application.StartupPath + @"\file.dat");
                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
                XF_Main.WriteErrorLog("4");
                while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
                {
                    memStream.Write(buffer, 0, bytesRead);
                }
                memStream.Write(Encoding.UTF8.GetBytes(postdata), 0, Encoding.UTF8.GetBytes(postdata).Length);

                // 写入最后的结束边界符
                memStream.Write(endBoundary, 0, endBoundary.Length);

                request.ContentLength = memStream.Length;
                XF_Main.WriteErrorLog("5");
                //UTF8Encoding encoding = new UTF8Encoding();
                //ASCIIEncoding encoding = new ASCIIEncoding();

                //byte[] data = encoding.GetBytes(postdata);//post 方式的编码    
                //byte[] data = Encoding.UTF8.GetBytes(postdata);//post 方式的编码    
                //XF_Main.WriteErrorLog("21");
                //request.Headers.Clear();
                //request.ServicePoint.ConnectionLimit
              
                //request.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0; .NET CLR 2.0.50727; .NET4.0C; .NET4.0E)";
                //request.Headers.Add("Accept-Language", "zh-cn");
                //request.Headers.Add("Accept-Encoding", "gzip, deflate");
                //request.Accept = "application/x-shockwave-flash, image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/xaml+xml, application/vnd.ms-xpsdocument, application/x-ms-xbap, application/x-ms-application, application/msword, application/vnd.ms-excel, application/vnd.ms-powerpoint, */*";
                //request.Host = "10.158.249.36";
                
                //request.PreAuthenticate = true;
                //request.Credentials = CredentialCache.DefaultCredentials;               
                
                //XF_Main.WriteErrorLog("3");
                //提交请求
                stream = request.GetRequestStream();

                memStream.Position = 0;
                var tempBuffer = new byte[memStream.Length];
                memStream.Read(tempBuffer, 0, tempBuffer.Length);
                memStream.Close();
                
                stream.Write(tempBuffer, 0, tempBuffer.Length);
                stream.Close();

                //接收                
                HttpWebResponse response = (HttpWebResponse)request.GetResponse(); //XF_Main.WriteErrorLog("4");
                if (response.StatusCode != HttpStatusCode.OK)
                    return false;

                //StreamReader streamReader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("utf-8"));
                //StreamReader streamReader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                StreamReader streamReader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                result = streamReader.ReadToEnd();
                request.Abort();
                response.Close();
                streamReader.Close();
                cCurrent = null;

                return st;
            }
            catch (Exception ex) { XF_Main.WriteErrorLog(ex.Message + "\r\n" + ex.StackTrace); st = false; return false; } return st;
        }

public static string GetMultipartData(string postdata, string boundary)
        {            
            array = postdata.Split('&');
            datas = new StringBuilder();
            foreach (string str in array)
            {
                string[] arr = str.Split('=');
                //if (str.Contains("wkstAttach"))
                //    datas.AppendFormat("-----------------------------{0}\r\nContent-Disposition: form-data; name=\"{1}\"; filename=\"\"\r\nContent-Type: application/octet-stream\r\n\r\n{2}\r\n", boundary, arr[0], arr[1]);
                //else
                datas.AppendFormat("-----------------------------{0}\r\nContent-Disposition: form-data; name=\"{1}\"\r\n\r\n{2}\r\n", boundary, arr[0], arr[1]);                                    
            }
            datas.AppendFormat("-----------------------------{0}--\r\n", boundary);
            return datas.ToString();
        }
小道消息 2014-11-29
  • 打赏
  • 举报
回复
boundary=---------------------------7de1863814700f2 这个是动态的,请求了几次这个值都不一样
WM_JAWIN 2014-11-28
  • 打赏
  • 举报
回复
是不是多了两个--,之前我也弄这个东西,估计是那个-号的问题。多一个少一个都不行,你捉个标准的对比一下吧
S314324153 2014-11-28
  • 打赏
  • 举报
回复
光有错误信息,看不出多少门道啊,不如贴上部分代码
phommy 2014-11-28
  • 打赏
  • 举报
回复
http://www.telerik.com/fiddler/add-ons 有fiddler抓,然后在这里下个配套的代码生成器,直接把请求拖到code页就帮你生成代码了
WorldMobile 2014-11-28
  • 打赏
  • 举报
回复
应该是你生成的数据有问题了,可以参考一下这个链接 http://blog.csdn.net/flymorn/article/details/6769722
失落的神庙 2014-11-28
  • 打赏
  • 举报
回复
一般用 UTF-8就行了。
小道消息 2014-11-27
  • 打赏
  • 举报
回复
cookie postdata数据都拿到了 就是不知道 提交数据编码
小道消息 2014-11-27
  • 打赏
  • 举报
回复
引用 1 楼 sp1234 的回复:
你要了解 RFC2188 协议以及后续的扩展协议,你提交的 body 数据格式要符合人家的规范。
这是我httpwatch抓到的东西 POST /web/scc/sflow/distributetask/distributeTask.do?action=saveAndSend HTTP/1.1 Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/msword, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/xaml+xml, application/x-ms-xbap, application/x-ms-application, */* Referer: http://10.158.249.36/web/scc/sflow/distributetask/distributeTask.do?action=init&activity=sgcsc002&processType=109&processNo=10903&appNo=141127765087&taskID=315649188&orgNo=3740403&actName=%E5%9C%B0%E5%B8%82%E6%8E%A5%E5%8D%95%E6%B4%BE%E5%B7%A5 Accept-Language: zh-cn Content-Type: multipart/form-data; boundary=---------------------------7de1863814700f2 UA-CPU: x86 Accept-Encoding: gzip, deflate User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 2.0.50727; .NET4.0C; .NET4.0E) Host: 10.158.249.36 Content-Length: 2383 Connection: Keep-Alive Cache-Control: no-cache Cookie: logonUsername=88882; ZP_CAL=%27fdow%27%3Anull%2C%27history%27%3A%222014/11/26/23/59%2C2014/11/26/23/59%2C2014/12/26/23/59%2C2014/12/27/23/59%2C2014/11/26/00/00%2C2014/11/27/00/00%2C2014/11/27/00/00%2C2014/11/26/00/00%2C2014/11/26/00/00%22%2C%27sortOrder%27%3A%22asc%22%2C%27hsize%27%3A9; JSESSIONID=vyvLJ2yL3nTvpGsXY10n7rXnbq6TFvwGsNMrfQkvX9bTJFhL7DZw!2142538846 -----------------------------7de1863814700f2 Content-Disposition: form-data; name="siteTypeCode" 02 -----------------------------7de1863814700f2 Content-Disposition: form-data; name="appointReason" -----------------------------7de1863814700f2 Content-Disposition: form-data; name="bookingTime" -----------------------------7de1863814700f2 Content-Disposition: form-data; name="acceptTime" 2014-11-27 09:17 -----------------------------7de1863814700f2 Content-Disposition: form-data; name="appNo" 141127765087 -----------------------------7de1863814700f2 Content-Disposition: form-data; name="taskId" 315649188 -----------------------------7de1863814700f2 Content-Disposition: form-data; name="vheicleId" -----------------------------7de1863814700f2 Content-Disposition: form-data; name="reapairEmpNoName" 瀛熷簞鎶慨缁? -----------------------------7de1863814700f2 Content-Disposition: form-data; name="reapairEmpNo" 瀛熷簞鎶慨缁? -----------------------------7de1863814700f2 Content-Disposition: form-data; name="repairOrg" 374040304 -----------------------------7de1863814700f2 Content-Disposition: form-data; name="repairDeptNo" 0001488348 -----------------------------7de1863814700f2 Content-Disposition: form-data; name="dispachTime" 2014-11-27 09:17:47 -----------------------------7de1863814700f2 Content-Disposition: form-data; name="normalOpinion" 5050074696 -----------------------------7de1863814700f2 Content-Disposition: form-data; name="handleOpinion" 璇峰鐞嗭紝骞舵寜銆婃灒搴勫叕鍙?5598涓氬姟宸ュ崟濉啓鎵嬪唽銆嬭繘琛屽弽棣堣澶勭悊 -----------------------------7de1863814700f2 Content-Disposition: form-data; name="wkstAttach.contentFile"; filename="" Content-Type: application/octet-stream -----------------------------7de1863814700f2 Content-Disposition: form-data; name="forkValue" 鏁呴殰澶勭悊 -----------------------------7de1863814700f2 Content-Disposition: form-data; name="flowHandleDept" 0010924641 -----------------------------7de1863814700f2 Content-Disposition: form-data; name="isSmsNotice" 1 -----------------------------7de1863814700f2 Content-Disposition: form-data; name="orgNo" 3740403 -----------------------------7de1863814700f2 Content-Disposition: form-data; name="countyCode" 370402 -----------------------------7de1863814700f2--
  • 打赏
  • 举报
回复
你要了解 RFC2188 协议以及后续的扩展协议,你提交的 body 数据格式要符合人家的规范。

111,094

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • AIGC Browser
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧