将Http请求读取到Byte数组中

本文关键字:Byte 数组 读取 Http 请求 | 更新日期: 2023-09-27 18:29:37

我正在开发一个网页,该网页需要接受HTTP Post Request并将其读取到字节数组中以进行进一步处理。我有点纠结于如何做到这一点,我也纠结于什么是最好的方法。这是我到目前为止的代码:

 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[]字段。

谢谢!

将Http请求读取到Byte数组中

最简单的方法是将其复制到MemoryStream,然后在需要时调用ToArray

如果你使用的是.NET4,那真的很简单:

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

编辑:如果您不使用.NET4,您可以创建自己的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);
    }
}

您只需使用WebClient即可。。。

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

其中..是数据的URL地址。

我使用MemoryStreamResponse.GetResponseStream().CopyTo(stream)

HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(url);
myRequest.Method = "GET";
WebResponse myResponse = myRequest.GetResponse();
MemoryStream ms = new MemoryStream();
myResponse.GetResponseStream().CopyTo(ms);
byte[] data = ms.ToArray();

我有一个函数可以通过发送响应流来实现这一点:

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

对于所有这些情况,当您的上下文。Request.ContentLength大于零,您可以简单地执行:

byte[] contentBytes = context.Request.BinaryRead(context.Request.ContentLength);

这对我有效:

    MemoryStream ms = new MemoryStream();
    await HttpContext.Request.Body.CopyToAsync(ms);
    byte[] fileBytes = ms.ToArray();