首页 > 代码库 > .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; }
.net HttpWebRequest 模拟form提交
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。