C#中HttpWebRequest用Post提交Content-Type: multipart/form-data; boundary=


在C#中有HttpWebRequest類,可以很方便用來獲取http請求,但是這個類對Post方式沒有提供一個很方便的方法來獲取數據。網上有很多人提供了解決方法,但都參差不齊,這里我把我使用的方法總結出來,與大家分享。

本文精華:實現了post的時候即可以有字符串的key-value,還可以帶文件。

Post數據格式

Post提交數據的時候最重要就是把Key-Value的數據放到http請求流中,而HttpWebRequest沒有提供一個屬性之類的東西可以讓我們自由添加Key-Value,因此就必須手工構造這個數據。

根據RFC 2045協議,一個Http Post的數據格式如下:

[html] view plain copy
  1. Content-Type: multipart/form-data; boundary=AaB03x  
  2.   
  3.  --AaB03x  
  4.  Content-Disposition: form-data; name="submit-name"  
  5.   
  6.  Larry  
  7.  --AaB03x  
  8.  Content-Disposition: form-data; name="file"; filename="file1.dat"  
  9.  Content-Type: application/octet-stream  
  10.   
  11.  ... contents of file1.dat ...  
  12.  --AaB03x--  


詳細解釋如下:

Content-Type: multipart/form-data; boundary=AaB03x

如上面所示,首先聲明數據類型為multipart/form-data, 然后定義邊界字符串AaB03x,這個邊界字符串就是用來在下面來區分各個數據的,可以隨便定義,但是最好是用破折號等數據中一般不會出現的字符。然后是換行符。

注意:Post中定義的換行符是\r\n

--AaB03x

這個是邊界字符串,注意每一個邊界符前面都需要加2個連字符“--”,然后跟上換行符。

Content-Disposition: form-data; name="submit-name"

這里是Key-Value數據中字符串類型的數據。 submit-name 是這個Key-Value數據中的Key。當然也需要換行符。

Larry

這個就是剛才Key-Value數據中的value。

--AaB03x

邊界符,表示數據結束。

Content-Disposition: form-data; name="file"; filename="file1.dat"

這個代表另外一個數據,它的key是file,文件名是file1.dat。 注意:最后面沒有分號了。

Content-Type: application/octet-stream

這個標識文件類型。application/octet-stream表示二進制數據。

... contents of file1.dat ...

這個是文件內容。可以使二進制的數據。

--AaB03x--

數據結束后的分界符,注意因為這個后面沒有數據了所以需要在后面追加一個“--”表示結束。

C#下Post數據的函數

搞明白格式后,我們就很容易寫出C#的代碼了。如下所示:

[csharp] view plain copy
  1. private static string HttpPostData(string url, int timeOut, string fileKeyName,   
  2.                                     string filePath, NameValueCollection stringDict)  
  3. {  
  4.     string responseContent;  
  5.     var memStream = new MemoryStream();  
  6.     var webRequest = (HttpWebRequest)WebRequest.Create(url);  
  7.     // 邊界符  
  8.     var boundary = "---------------" + DateTime.Now.Ticks.ToString("x");  
  9.     // 邊界符  
  10.     var beginBoundary = Encoding.ASCII.GetBytes("--" + boundary + "\r\n");  
  11.     var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);  
  12.     // 最后的結束符  
  13.     var endBoundary = Encoding.ASCII.GetBytes("--" + boundary + "--\r\n");  
  14.   
  15.     // 設置屬性  
  16.     webRequest.Method = "POST";  
  17.     webRequest.Timeout = timeOut;  
  18.     webRequest.ContentType = "multipart/form-data; boundary=" + boundary;  
  19.   
  20.     // 寫入文件  
  21.     const string filePartHeader =  
  22.         "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n"+  
  23.          "Content-Type: application/octet-stream\r\n\r\n";  
  24.     var header = string.Format(filePartHeader, fileKeyName, filePath);  
  25.     var headerbytes = Encoding.UTF8.GetBytes(header);  
  26.   
  27.     memStream.Write(beginBoundary, 0, beginBoundary.Length);  
  28.     memStream.Write(headerbytes, 0, headerbytes.Length);  
  29.   
  30.     var buffer = new byte[1024];  
  31.     int bytesRead; // =0  
  32.   
  33.     while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)  
  34.     {  
  35.         memStream.Write(buffer, 0, bytesRead);  
  36.     }  
  37.   var contentLine = Encoding.ASCII.GetBytes( "\r\n");  memStream.Write(contentLine, 0, contentLine.Length); 
  38.     // 寫入字符串的Key  
  39.     var stringKeyHeader = "\r\n--" + boundary +  
  40.                            "\r\nContent-Disposition: form-data; name=\"{0}\""+  
  41.                            "\r\n\r\n{1}\r\n";  
  42.   
  43.     foreach (byte[] formitembytes in from string key in stringDict.Keys  
  44.                                      select string.Format(stringKeyHeader, key, stringDict[key])  
  45.                                          into formitem  
  46.                                          select Encoding.UTF8.GetBytes(formitem))  
  47.     {  
  48.         memStream.Write(formitembytes, 0, formitembytes.Length);  
  49.     }  
  50.   
  51.     // 寫入最后的結束邊界符  
  52.     memStream.Write(endBoundary, 0, endBoundary.Length);  
  53.   
  54.     webRequest.ContentLength = memStream.Length;  
  55.   
  56.     var requestStream = webRequest.GetRequestStream();  
  57.   
  58.     memStream.Position = 0;  
  59.     var tempBuffer = new byte[memStream.Length];  
  60.     memStream.Read(tempBuffer, 0, tempBuffer.Length);  
  61.     memStream.Close();  
  62.   
  63.     requestStream.Write(tempBuffer, 0, tempBuffer.Length);  
  64.     requestStream.Close();  
  65.   
  66.     var httpWebResponse = (HttpWebResponse)webRequest.GetResponse();  
  67.   
  68.     using (var httpStreamReader = new StreamReader(httpWebResponse.GetResponseStream(),   
  69.                                                     Encoding.GetEncoding("utf-8")))  
  70.     {  
  71.         responseContent = httpStreamReader.ReadToEnd();  
  72.     }  
  73.   
  74.     fileStream.Close();  
  75.     httpWebResponse.Close();  
  76.     webRequest.Abort();  
  77.   
  78.     return responseContent;  
  79. }  




參考資料
  1. Rfc2045:http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.
  2. http://stackoverflow.com/questions/566462/upload-files-with-httpwebrequest-multipart-form-data
  3. VIA : http://hi.baidu.com/zkbob22/blog/item/0638f93931209ae0b211c7b8.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM