content-Type: multipart/form-data
boundary=ceshi(分组)
请求体中是按照一定格式拼的串,大致就是--ceshi **** --ceshi **** --ceshi **** --ceshi-- 这样的格式。
因为最终是发送请求流,这些请求体中的内容都需要写进请求流中,虽然有些事字符串这种文本类型的数据,但是文件本身是二进制的,所以我就把所有文本都变成了二进制,再加上文件本身,
然后按照这种格式的顺序写入请求流中,最后发送出去(如果不变成二进制,则只能进行文本类型的文件上传,限制很多,并且容易损坏文件)。
代码如下:
把C盘下的2.html文件发送了出去(图片、pdf 等类型也是可用的,因为都是转成了二进制)已经过测试
private void post1() { string url = @"http://*******";//这里就不暴露我们的地址啦 string modelId = "4f1e2e3d-6231-4b13-96a4-835e5af10394"; string updateTime = "2016-11-03 14:17:25"; string encrypt = "f933797503d6e2c36762428a280e0559"; string filePath = @"C:/2.html"; string fileName = "2.html"; byte[] fileContentByte = new byte[1024]; // 文件内容二进制 #region 将文件转成二进制 FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read); fileContentByte = new byte[fs.Length]; // 二进制文件 fs.Read(fileContentByte, 0, Convert.ToInt32(fs.Length)); fs.Close(); #endregion #region 定义请求体中的内容 并转成二进制 string boundary = "ceshi"; string Enter = " "; string modelIdStr = "--" + boundary + Enter + "Content-Disposition: form-data; name="modelId"" + Enter + Enter + modelId + Enter; string fileContentStr = "--" + boundary + Enter + "Content-Type:application/octet-stream" + Enter + "Content-Disposition: form-data; name="fileContent"; filename="" + fileName + """ + Enter + Enter; string updateTimeStr = Enter + "--" + boundary + Enter + "Content-Disposition: form-data; name="updateTime"" + Enter + Enter + updateTime; string encryptStr = Enter + "--" + boundary + Enter + "Content-Disposition: form-data; name="encrypt"" + Enter + Enter + encrypt + Enter + "--" + boundary + "--"; var modelIdStrByte = Encoding.UTF8.GetBytes(modelIdStr);//modelId所有字符串二进制 var fileContentStrByte = Encoding.UTF8.GetBytes(fileContentStr);//fileContent一些名称等信息的二进制(不包含文件本身) var updateTimeStrByte = Encoding.UTF8.GetBytes(updateTimeStr);//updateTime所有字符串二进制 var encryptStrByte = Encoding.UTF8.GetBytes(encryptStr);//encrypt所有字符串二进制 #endregion HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "POST"; request.ContentType = "multipart/form-data;boundary=" + boundary; Stream myRequestStream = request.GetRequestStream();//定义请求流 #region 将各个二进制 安顺序写入请求流 modelIdStr -> (fileContentStr + fileContent) -> uodateTimeStr -> encryptStr myRequestStream.Write(modelIdStrByte, 0, modelIdStrByte.Length); myRequestStream.Write(fileContentStrByte, 0, fileContentStrByte.Length); myRequestStream.Write(fileContentByte, 0, fileContentByte.Length); myRequestStream.Write(updateTimeStrByte, 0, updateTimeStrByte.Length); myRequestStream.Write(encryptStrByte, 0, encryptStrByte.Length); #endregion HttpWebResponse response = (HttpWebResponse)request.GetResponse();//发送 Stream myResponseStream = response.GetResponseStream();//获取返回值 StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8")); string retString = myStreamReader.ReadToEnd(); myStreamReader.Close(); myResponseStream.Close(); }