首页 > 代码库 > .net HttpWebRequest 模拟form提交

.net HttpWebRequest 模拟form提交

技术分享View Code
技术分享
private static Stream GetPostStream(string filePath, NameValueCollection formData, string boundary)        {            Stream postDataStream = new System.IO.MemoryStream();            //adding form data            string formDataHeaderTemplate = Environment.NewLine + "--" + boundary + Environment.NewLine +            "Content-Disposition: form-data; name=\"{0}\";" + Environment.NewLine + Environment.NewLine + "{1}";            foreach (string key in formData.Keys)            {                byte[] formItemBytes = System.Text.Encoding.UTF8.GetBytes(string.Format(formDataHeaderTemplate,                key, formData[key]));                postDataStream.Write(formItemBytes, 0, formItemBytes.Length);            }            //adding file data            FileInfo fileInfo = new FileInfo(filePath);            string fileHeaderTemplate = Environment.NewLine + "--" + boundary + Environment.NewLine +            "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"" +            Environment.NewLine + "Content-Type: image/jpeg" + Environment.NewLine + Environment.NewLine;            byte[] fileHeaderBytes = System.Text.Encoding.UTF8.GetBytes(string.Format(fileHeaderTemplate,            "UploadCSVFile", fileInfo.FullName));            postDataStream.Write(fileHeaderBytes, 0, fileHeaderBytes.Length);            FileStream fileStream = fileInfo.OpenRead();            byte[] buffer = new byte[1024];            int bytesRead = 0;            while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)            {                postDataStream.Write(buffer, 0, bytesRead);            }            fileStream.Close();            byte[] endBoundaryBytes = System.Text.Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");            postDataStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);            return postDataStream;        }
View Code

 

.net HttpWebRequest 模拟form提交