Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 5 HttpClient post raw binary data

My WebApp needs to communicate with my server via ProtBuf. For this to be possible, I need to be able to post the raw binary data.

This is the code I'm using right now. The problem with this is that HttpClient encodes the Uint8Array as a JSON array, so that the result is not a valid protobuffer anymore:

const message = LoginRequest.fromObject({
  code: code,
  username: username,
  password: password
});

const buffer: Uint8Array = LoginRequest.encode(message).finish();

this.http.post('https://api.myserver.com', buffer)
  .subscribe(/*...*/);

HttpClient.post accepts some options, where you can set responseType to json, text, blob or arraybuffer. But this just sets the expected type of the response, the body of the request still gets encoded as JSON.

Does HttpClient have the possibility to send unencoded bodies?

Edit: This is the body I receive at the server:

{"0":10,"1":3,"2":97,"3":98,"4":99,"5":18,"6":5,"7":97,"8":100,"9":109,"10":105,"11":110,"12":26,"13":8,"14":112,"15":97,"16":115,"17":115,"18":119,"19":111,"20":114,"21":100}

like image 494
Martin Fink Avatar asked Dec 23 '22 10:12

Martin Fink


1 Answers

As it can be seen in the reference, the type of request body is any, this suggests that it is free-form. HttpClient uses HttpRequest to represent requests, which uses serializeBody method to transform request body:

Transform the free-form body into a serialized format suitable for transmission to the server.

It accepts a number of body types, all of them are stringified accordingly. Raw body is expected to be Blob, ArrayBuffer or a string. So Uint8Array should be converted to one of them, for example:

const arr: Uint8Array = LoginRequest.encode(message).finish();
const buffer: ArrayBuffer = arr.buffer;
like image 129
Estus Flask Avatar answered Jan 04 '23 04:01

Estus Flask