将Http请求读入字节数组

问题描述 投票:31回答:6

我正在开发一个网页,该网页需要接收HTTP Post请求并将其读入字节数组以进行进一步处理。我对如何做到这一点有些固执,对什么才是最好的实现方式感到困惑。到目前为止,这是我的代码:

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

谢谢!

c# asp.net httpcontext system.web
6个回答
57
投票

最简单的方法是将其复制到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);
    }
}

17
投票

您可以仅使用WebClient ...

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

..是数据的URL地址。


1
投票

我有一个通过发送响应流来做到这一点的功能:

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

1
投票

我使用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();

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
投票

对于所有当context.Request.ContentLength大于零的情况,您可以简单地做:

byte[] contentBytes = context.Request.BinaryRead(context.Request.ContentLength);
© www.soinside.com 2019 - 2024. All rights reserved.