2012-03-30 65 views
24

我正在開發一個需要採用HTTP Post Request並將其讀取到字節數組中進行進一步處理的Web頁面。我一直在堅持如何做到這一點,而且我很難完成什麼是最好的方法。這是我到目前爲止的代碼:將Http請求讀入字節數組

public override void ProcessRequest(HttpContext curContext) 
    { 
     if (curContext != null) 
     { 
      int totalBytes = curContext.Request.TotalBytes; 
      string encoding = curContext.Request.ContentEncoding.ToString(); 
      int reqLength = curContext.Request.ContentLength; 
      long inputLength = curContext.Request.InputStream.Length; 
      Stream str = curContext.Request.InputStream; 

     } 
     } 

我檢查的要求和等於128現在做我只需要使用一個Stream對象進入它的byte []格式的總字節的長度?我正朝着正確的方向走嗎?不知道如何繼續。任何建議都會很棒。我需要將整個HTTP請求放到byte []字段中。

謝謝!

回答

50

最簡單的方法是將其複製到MemoryStream - 如果需要,請致電ToArray

如果您使用.NET 4,這是非常簡單:

MemoryStream ms = new MemoryStream(); 
curContext.Request.InputStream.CopyTo(ms); 
// If you need it... 
byte[] data = ms.ToArray(); 

編輯:如果你不使用.NET 4,你可以創建自己的CopyTo從實施的。下面是它作爲一個擴展方法的版本:

public static void CopyTo(this Stream source, Stream destination) 
{ 
    // TODO: Argument validation 
    byte[] buffer = new byte[16384]; // For example... 
    int bytesRead; 
    while ((bytesRead = source.Read(buffer, 0, buffer.Length)) > 0) 
    { 
     destination.Write(buffer, 0, bytesRead); 
    } 
} 
+0

我沒有.CopyTo? – Encryption 2012-03-30 18:37:15

+0

如何在不使用.CopyTo選項的情況下使用內存流? – Encryption 2012-03-30 18:39:53

+0

@加密:你可以自己實現一些非常相似的東西 - 我將在一分鐘內編輯它... – 2012-03-30 18:40:24

0
class WebFetch 
{ 
static void Main(string[] args) 
{ 
    // used to build entire input 
    StringBuilder sb = new StringBuilder(); 

    // used on each read operation 
    byte[] buf = new byte[8192]; 

    // prepare the web page we will be asking for 
    HttpWebRequest request = (HttpWebRequest) 
     WebRequest.Create(@"http://www.google.com/search?q=google"); 

    // execute the request 
    HttpWebResponse response = (HttpWebResponse) 
     request.GetResponse(); 

    // we will read data via the response stream 
    Stream resStream = response.GetResponseStream(); 

    string tempString = null; 
    int count = 0; 

    do 
    { 
     // fill the buffer with data 
     count = resStream.Read(buf, 0, buf.Length); 

     // make sure we read some data 
     if (count != 0) 
     { 
      // translate from bytes to ASCII text 
      tempString = Encoding.ASCII.GetString(buf, 0, count); 

      // continue building the string 
      sb.Append(tempString); 
     } 
    } 
    while (count > 0); // any more data to read? 

    // print out page source 
    Console.WriteLine(sb.ToString()); 
    Console.Read(); 
    } 
} 
+0

好的代碼,但它假定正在提取的數據是字符串數據。如果它是一個需要保存爲字節的文件或其他東西,這不是實現它的方法。儘管如此,我也不會投票贊成。 – vapcguy 2017-10-16 19:34:42

12

您可以只使用Web客戶端爲...

WebClient c = new WebClient(); 
byte [] responseData = c.DownloadData(..) 

哪裏..是URL地址中的數據。

+0

請注意,DownloadData不會爲4xx和5xx引發異常 – Nathan 2017-11-09 06:34:22

0

我有這樣做,通過響應流發送功能:

private byte[] ReadFully(Stream input) 
{ 
    try 
    { 
     int bytesBuffer = 1024; 
     byte[] buffer = new byte[bytesBuffer]; 
     using (MemoryStream ms = new MemoryStream()) 
     { 
      int readBytes; 
      while ((readBytes = input.Read(buffer, 0, buffer.Length)) > 0) 
      { 
       ms.Write(buffer, 0, readBytes); 
      } 
      return ms.ToArray(); 
     } 
    } 
    catch (Exception ex) 
    { 
     // Exception handling here: Response.Write("Ex.: " + ex.Message); 
    } 
} 

既然你有Stream str = curContext.Request.InputStream;,然後你可以只是做:

byte[] bytes = ReadFully(str); 

如果你已經做到了這一點:

HttpWebRequest req = (HttpWebRequest)WebRequest.Create(someUri); 
req.Credentials = CredentialCache.DefaultCredentials; 
HttpWebResponse resp = (HttpWebResponse)req.GetResponse(); 

你會說它是這樣:

byte[] bytes = ReadFully(resp.GetResponseStream());