HttpWebRequest post "multipart/form-data"类型的web数据

本文介绍如何使用C#手动构造multipart/form-data格式的数据包来上传文件,包括设置请求头、构造请求体及发送POST请求的具体步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

webRqst.ContentType   =   "multipart/form-data;   boundary=xyz";  
  所以数据提交部份实际上是从你的boundary也就是  
  -----------------------------7d42bf2030536开始到结束。  
  以下是一个例子:  
   
  System.Uri   uri   =   new   Uri(msp_url);    
  string   dataBoundary   =   "--xyz";    
  System.Net.HttpWebRequest   webRqst   =   (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(uri);    
   
  //add   existing   cookies   to   the   webrequest.    
  webRqst.CookieContainer   =   new   CookieContainer();    
  webRqst.CookieContainer.Add(mspCookies);    
   
  //create   the   WebRequest   Content-Body   manually   for   file   upload.    
  webRqst.ContentType   =   "multipart/form-data;   boundary=xyz";    
  webRqst.Method   =   "POST";    
  webRqst.KeepAlive   =   true;    
   
  //get   the   file   content   that   will   be   uploaded.    
  StreamReader   sr   =   new   StreamReader(filepath);    
  string   FileData   =   sr.ReadToEnd();   //   test   data   to   send.    
  sr.Close();    
   
  //make   a   string   to   store   the   content.    
  StringBuilder   DataString   =   new   StringBuilder();    
   
  DataString.Append(dataBoundary   +   "/r/n");    
  DataString.Append("Content-Disposition:   form-data;   name=/"filename/"/r/n/r/n"   +   "test.txt/r/n");    
   
  DataString.Append(dataBoundary   +   "/r/n");    
  DataString.Append("Content-Disposition:   form-data;   name="   +   "/"submitFile/""   +    
  ";   filename="   +   "/""   +   filename   +   "/""   +   "/r/n");    
  DataString.Append("Content-Type:   text/plain/r/n/r/n");    
  DataString.Append(FileData);    
  DataString.Append(dataBoundary   +   "--/r/n");    
   
  byte   []Postdata   =   System.Text.Encoding.Default.GetBytes(DataString.ToString());    
   
  //change   the   requests   content   length   to   the   size   of   data   being   posted   in   request.    
  webRqst.ContentLength   =   Postdata.Length;    
   
  //get   the   response   stream   from   the   webrequest   and   write   the   data   to   be   posted   to   the    
  //Request   Stream    
   
  Stream   tempStream   =   webRqst.GetRequestStream();    
  tempStream.Write(Postdata,0,Postdata.Length);    
  tempStream.Flush();    
  tempStream.Close();    
   
   
  //change   certificate   policy   to   always   allow.    
  System.Net.ServicePointManager.CertificatePolicy   =   new   MyPolicy();    
  System.Net.HttpWebResponse   webRsp   =   (System.Net.HttpWebResponse)webRqst.GetResponse();    

[抄录]http://topic.youkuaiyun.com/t/20040621/10/3109172.html

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值