Question

I'm sending a request using ServerXMLHTTP and using HTTPRequester plugin I can see that the response for my request is raw binary data of the requested file. I need to read and save this binary data in a Byte[] but I keep getting the error : End of file reached in invalid state for current encoding.

Here's my code:

 ServerXMLHTTP HTTPRequest=new ServerXMLHTTP();
 HTTPRequest.open("POST",@"https://thetargetwebsite/",false);
 HTTPRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
 HTTPRequest.send("file_id=" + file_id);
string binaryfile=HTTPRequest.responseText; // causes the error
//OR
System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
byte[] bytes = encoding.GetBytes(HTTPRequest.responseText); // also causes the error

Can you help me with how to read the reponse text with binary data ?

EDIT: If I'm not to use ServerXMLHTTP what should I use instead ?

Was it helpful?

Solution

I used this instead and it worked fine:

         byte[] result;
         byte[] buffer = new byte[4096];

         System.Net.WebRequest wr = System.Net.WebRequest.Create(url);

         using (System.Net.WebResponse response = wr.GetResponse())
         {
             using (Stream responseStream = response.GetResponseStream())
             {
                 using (MemoryStream memoryStream = new MemoryStream())
                 {
                     int count = 0;
                     do
                     {
                         count = responseStream.Read(buffer, 0, buffer.Length);
                         memoryStream.Write(buffer, 0, count);

                     } while (count != 0);

                     result = memoryStream.ToArray();

                 }
             }
         }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top