通过WebClient / HttpWebRequest提交XLS文件

时间:2013-12-16 20:44:47

标签: c# httpwebrequest webclient

我正在尝试使用WebClient / HttpWebRequest提交XLS文件。该网页已获得<input type="file" name="FileSubmitted">

我尝试使用帖子https://stackoverflow.com/a/2996904/521973中提供的代码,但是我收到了错误消息 “ System.Net.WebException:远程服务器返回错误:(500)内部服务器错误”。当我展开异常细节时,我看到“ System.Net.WebExceptionStatus.ProtocolError

我在浏览器中看到的标题 请求标题:

Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8
Cache-Control:max-age=0
Connection:keep-alive
Content-Length:49504
Content-Type:multipart/form-data; boundary=----WebKitFormBoundary9ewWOMyBmk0YAhTL
Cookie:SFID=111222; SFTOKEN=ec60368c2e5799df-FC5E1D12-CD2A-CA0C-593E4F9DC26A8123
Host:secure.sampleweb.com
Origin:https://secure.sampleweb.com
Referer:https://secure.sampleweb.com/submit/submit.cfm?SFID=111222&SFTOKEN=ec60368c2e5799df-FC5E1D12-CD2A-CA0C-593E4F9DC26A8123
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36

请求有效负载

------WebKitFormBoundary9ewWOMyBmk0YAhTL
Content-Disposition: form-data; name="FileSubmitted"; filename="Sample.xls"
Content-Type: application/vnd.ms-excel


------WebKitFormBoundary9ewWOMyBmk0YAhTL
Content-Disposition: form-data; name="FileSubmittedValue"

C:\filepath\Sample.xls
------WebKitFormBoundary9ewWOMyBmk0YAhTL--

代码:

        static void Main()
        {
            NameValueCollection postData = new NameValueCollection();
            postData["WebUser"] = "abc";
            postData["WebPass"] = "xyz";

            byte[] responseBytes = webClient.UploadValues(URLAuth, "POST", postData);
            string resultAuthTicket = Encoding.UTF8.GetString(responseBytes);

            CookieCollection cookies = webClient.CookieContainer.GetCookies(new Uri(URLAuth));

            string URL = "https://secure.sampleweb.com/submit/submit.cfm";
            string boundary = "----WebKitFormBoundary9ewWOMyBmk0YAhTL";
            System.Net.WebRequest webRequest = System.Net.WebRequest.Create(URL);

            string FilePath = "C:\\Sample.xls";
            HttpUploadFile(URL, FilePath, "FileSubmitted", "multipart/form-data", postData, boundary, cookies);
        }
        public static void HttpUploadFile(string url, string file, string paramName, string contentType, NameValueCollection nvc, string boundary, CookieCollection cookies)
        {
            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.Credentials = System.Net.CredentialCache.DefaultCredentials;
            wr.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
wr.CookieContainer = new CookieContainer();
            wr.CookieContainer.Add(cookies);
            wr.Host = "secure.sampleweb.com";
            wr.Referer = String.Format("https://secure.sampleweb.com/submit/submit.cfm?SFID={0}&SFTOKEN={1}", cookies[0].Value, cookies[1].Value);
            wr.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36";

            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
            {
                wresp = wr.GetResponse();
                Stream stream2 = wresp.GetResponseStream();
                StreamReader reader2 = new StreamReader(stream2);
            }
            catch (Exception ex)
            {
                if (wresp != null)
                {
                    wresp.Close();
                    wresp = null;
                }
            }
            finally
            {
                wr = null;
            }
        }

0 个答案:

没有答案