Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read Http Request into Byte array

I'm developing a web page that needs to take an HTTP Post Request and read it into a byte array for further processing. I'm kind of stuck on how to do this, and I'm stumped on what is the best way to accomplish. Here is my code so far:

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

I'm checking the length of the request and its total bytes which equals 128. Now do I just need to use a Stream object to get it into byte[] format? Am I going in the right direction? Not sure how to proceed. Any advice would be great. I need to get the entire HTTP request into byte[] field.

Thanks!

like image 647
Encryption Avatar asked Mar 30 '12 18:03

Encryption


2 Answers

The simplest way is to copy it to a MemoryStream - then call ToArray if you need to.

If you're using .NET 4, that's really easy:

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

EDIT: If you're not using .NET 4, you can create your own implementation of CopyTo. Here's a version which acts as an extension method:

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);     } } 
like image 186
Jon Skeet Avatar answered Oct 06 '22 04:10

Jon Skeet


You can just use WebClient for that...

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

Where .. is the URL address for the data.

like image 27
feroze Avatar answered Oct 06 '22 04:10

feroze