2017-09-13 61 views
1

問題上傳由部分數據:如何通過HttpWebRequest的

我想通過單一的http請求上傳由塊數據和顯示每個上傳後進展的變化(物理性通過Internet發送的數據)。 (現在並不重要,我將展示上傳進度,我可以簡單地將一些數據輸出到控制檯)。

代碼

Stackoverlow有很多這樣的問題: link 1等。(我不包括更多的鏈接,因爲我沒有足夠的聲望)。

using System; 
using System.Text; 
using System.IO; 
using System.Net; 

... 

public static void UploadData() 
{ 
    const string data = "simple string"; 
    byte[] buffer = new ASCIIEncoding().GetBytes(data); 

    // Thanks to http://www.posttestserver.com all is working from the box 
    HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://posttestserver.com/post.php"); 
    req.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/534.10 " + 
        "(KHTML, like Gecko) Chrome/8.0.552.224 Safari/534.10"; 
    req.Accept = "application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5"; 
    req.Headers.Add("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.3"); 
    req.Headers.Add("Accept-Language", "en-US,en;q=0.8"); 
    req.Method = "POST"; 
    req.ContentType = "application/x-www-form-urlencoded"; 
    req.ContentLength = buffer.Length;    
    req.SendChunked = true;    

    int bytesRead = buffer.Length; 
    const int chunkSize = 3; 
    Stream s = req.GetRequestStream(); 
    for (int offset = 0; offset < bytesRead; offset += chunkSize) 
    { 
     int bytesLeft = bytesRead - offset; 
     int bytesWrite = bytesLeft > chunkSize ? chunkSize : bytesLeft; 
     s.Write(buffer, offset, bytesWrite); 
    } 
    s.Close(); // IMPORTANT: only here all data will be send 
} 

備註

此外,根據 this link, 僅在每個發送過程中的每個寫入請求流必須發生,但在現實中(它可以在提琴手證明)發生的所有的發送操作在請求流關閉之後或僅通過響應獲取而不是更早。 (全部取決於SendChuncked,AllowWriteStreamBufferingContentLength參數,但在每次寫入流後都不會發送數據)。

問題

如何可以發送數據(物理)後,每寫(Write方法的每次調用)?

約束

  • 淨2.0;

  • 僅使用HttpWebRequest原語(不是WebClient)。

回答

0

因爲沒有人回答這個問題,而是由zergatul用戶這個問題已經回答了俄羅斯的計算器,我將在這裏發佈this answer from russian stackoverflow


答案
它的工作你如何預期。我使用了Microsoft網絡監視器。這是一個很好的工具,它是免費的(與httpdebugger相比)。我在Net 2.0中調試了你的代碼。

enter image description here

網絡監視器顯示每個3字節發送(我已採取較長的字符串)。

enter image description here

這裏文本 「PLE」( 「SIM PLE串」)已發送。

enter image description here


備註
在第一圖片中的字符串
// ВАЖНО: только здесь будут отправлены данные через сеть
意味着
// IMPORTANT: only here data will be sent over the net