Read Http Request into Byte array

后端 未结 6 1558
情话喂你
情话喂你 2021-02-05 01:15

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

6条回答
  •  执笔经年
    2021-02-05 01:41

    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:

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

提交回复
热议问题