0

I have the following code in C# that converts a string from one encoding to the other and send the response over http.

Everything in the code works fine. I'm just a bit confused

When I return this over http it gets converted into a text representation. I thought this would just send the raw byte array?

Why is it converted? Should I never try and send a raw byte array or is there a case for that when communicating over http? Or is a text representation and a application/octet-stream the way to send binary data over http?

byte[] fromBytes = fromEncoding.GetBytes(body);
byte[] toBytes = Encoding.Convert(fromEncoding, toEncoding, fromBytes);

var response = req.CreateResponse(HttpStatusCode.OK);
MemoryStream ms = new MemoryStream(toBytes);
response.Content = new StreamContent(ms);
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
return response;
Riri
  • 11,501
  • 14
  • 63
  • 88
  • Why are you messing with `Encoding` ? Is it binary, or is it text? – Lasse V. Karlsen Apr 21 '21 at 08:28
  • Well, the code changes encoding from one to another - and that works fine. The question more has to with the right way of handling binary responses over http. – Riri Apr 21 '21 at 08:29
  • And when you say "it gets converted into a string representation". What exactly is doing that conversion? How are you observing the response? And the binary data you're sending, is it really text? If it is really text, it could be that whatever tool you're using to look at the response with will use heuristics to try and determine the best way to present it to you, and landing on text. – Lasse V. Karlsen Apr 21 '21 at 08:31
  • Please know that text is also stored as "binary data", just a sequence of bytes. It's the interpretation of them that handles it as text. – Lasse V. Karlsen Apr 21 '21 at 08:32
  • Yeah. Sure everything is always just a sequence of bytes :). But as http in an layer on top of tcp that send a text representation - ref https://stackoverflow.com/questions/393407/why-http-protocol-is-designed-in-plain-text-way Is application/octet-stream then always the way to go when sending binary, application specific data? – Riri Apr 21 '21 at 09:35
  • Html has specialcharacter. See : https://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references?force_isolation=true. octet-stream stream is an encoding method the does not use the special HTML character. – jdweng Apr 21 '21 at 10:06
  • How do you observe the response? What kind of software or method are you using? – Lasse V. Karlsen Apr 21 '21 at 10:31

0 Answers0