2012-03-30 35 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オブジェクトを使用する必要があります等しい要求し、その合計のバイトの長さをチェックしていますか?私は正しい方向に進んでいますか?続行する方法がわからないどんなアドバイスも素晴らしいでしょう。 HTTP要求全体をbyte []フィールドに取得する必要があります。

ありがとうございます!

答えて

50

最も簡単な方法は、MemoryStreamにコピーしてから、必要に応じてToArrayに電話することです。

は、.NET 4を使用している場合、それは本当に簡単です:

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

EDIT:あなたは、.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

+0

.CopyToオプションを指定せずにメモリストリームを使用するにはどうすればよいですか? – Encryption

+0

@ Encryption:あなたは非常に似た何かを実装することができます - 私はそれを1分で編集します... –

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

12

あなたはちょうどそれのためのWebクライアントを使用することができます...

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

..は、データ用のURLアドレスです。

+0

'DownloadData'は4xxと5xxの例外をスローしません – Nathan

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); 

あなたがこれを行っていた場合:

byte[] bytes = ReadFully(resp.GetResponseStream()); 
関連する問題