C# 将 Http 请求读入字节数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9948463/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 11:20:57  来源:igfitidea点击:

Read Http Request into Byte array

c#asp.nethttpcontextsystem.web

提问by Encryption

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:

我正在开发一个需要接受 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;

         }
       }

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.

我正在检查请求的长度及其等于 128 的总字节数。现在我是否只需要使用 Stream 对象将其转换为 byte[] 格式?我是否朝着正确的方向前进?不知道如何继续。任何建议都会很棒。我需要将整个 HTTP 请求放入 byte[] 字段中。

Thanks!

谢谢!

采纳答案by Jon Skeet

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

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

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

如果您使用 .NET 4,那真的很简单:

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:

编辑:如果您不使用 .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);
    }
}

回答by Dasarp

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

回答by feroze

You can just use WebClient for that...

你可以只使用 WebClient ......

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

Where ..is the URL address for the data.

..数据的 URL 地址在哪里。

回答by vapcguy

I have a function that does it, by sending in the response stream:

我有一个函数可以通过在响应流中发送来完成它:

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

Since you have Stream str = curContext.Request.InputStream;, you could then just do:

既然你有Stream str = curContext.Request.InputStream;,你就可以这样做:

byte[] bytes = ReadFully(str);

If you had done this:

如果你这样做了:

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

You would call it this way:

你会这样称呼它:

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

回答by Phong Tran

I use MemoryStreamand Response.GetResponseStream().CopyTo(stream)

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

回答by Bruno Leit?o

For all those cases when your context.Request.ContentLength is greather than zero, you can simply do:

对于 context.Request.ContentLength 大于零的所有情况,您可以简单地执行以下操作:

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