HttpWebRequest post上传文件
2024-08-30 17:32:17
public static string HttpUploadFile(string url, string path)
{
// 设置参数
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
CookieContainer cookieContainer = new CookieContainer();
request.CookieContainer = cookieContainer;
request.AllowAutoRedirect = true;
request.Method = "POST";
string boundary = DateTime.Now.Ticks.ToString("X"); // 随机分隔线
request.ContentType = "multipart/form-data;charset=utf-8;boundary=" + boundary;
byte[] itemBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "\r\n");
byte[] endBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n"); int pos = path.LastIndexOf("\\");
string fileName = path.Substring(pos + ); //请求头部信息
StringBuilder sbHeader = new StringBuilder(string.Format("Content-Disposition:form-data;name=\"file\";filename=\"{0}\"\r\nContent-Type:application/octet-stream\r\n\r\n", fileName));
byte[] postHeaderBytes = Encoding.UTF8.GetBytes(sbHeader.ToString()); FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);
byte[] bArr = new byte[fs.Length];
fs.Read(bArr, , bArr.Length);
fs.Close(); Stream postStream = request.GetRequestStream();
postStream.Write(itemBoundaryBytes, , itemBoundaryBytes.Length);
postStream.Write(postHeaderBytes, , postHeaderBytes.Length);
postStream.Write(bArr, , bArr.Length);
postStream.Write(endBoundaryBytes, , endBoundaryBytes.Length);
postStream.Close(); //发送请求并获取相应回应数据
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
//直到request.GetResponse()程序才开始向目标网页发送Post请求
Stream instream = response.GetResponseStream();
StreamReader sr = new StreamReader(instream, Encoding.UTF8);
//返回结果网页(html)代码
string content = sr.ReadToEnd();
return content;
}
最新文章
- (转载)GDI+双缓冲
- JavaWeb前端基础复习笔记系列 一
- 值得 Web 开发人员收藏的20个 HTML5 实例教程
- spring容器初始化执行某个方法
- php 判断复选框checkbox是否被选中
- $().each() 与 $.each()解析
- leetcode Database2 (四)
- Codeforces 719 E. Sasha and Array (线段树+矩阵运算)
- ios开源项目(各种有用的第三方库)
- css两句话搞定漂亮表格样式
- ASP.NET中时间的绑定和格式化
- ubuntu 下安装Angular2-cli脚手架
- alpha-咸鱼冲刺day2-紫仪
- WC 2018 题解
- android屏蔽系统锁屏的办法
- 简单理解php深复制浅复制问题
- [Hinton] Neural Networks for Machine Learning - Hopfield Nets and Boltzmann Machine
- 深入探讨WPF的ListView控件
- xgboost学习与总结
- SSH框架整合的其它方式