我的 WebApp 需要通过 ProtBuf 与我的服务器通信。为此,我需要能够发布原始二进制数据。
这是我现在使用的代码。问题在于 HttpClient
将 Uint8Array 编码为 JSON 数组,因此结果不再是有效的 protobuffer:
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
接受一些选项,你可以设置responseType
为json
, text
, blob
或 arraybuffer
。但这只是设置了预期的响应类型,请求的主体仍然被编码为 JSON。
HttpClient
是否可以发送未编码的正文?
编辑:这是我在服务器上收到的正文:
{"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}
最佳答案
在reference中可以看出,请求body
的类型是any
,这表明它是自由格式的。 HttpClient
使用HttpRequest
表示请求,它使用serializeBody
method转换请求体:
Transform the free-form body into a serialized format suitable for transmission to the server.
它接受多种主体类型,所有主体类型都相应地进行了字符串化。原始主体应为 Blob
、ArrayBuffer
或字符串。所以Uint8Array
应该转换为其中之一,例如:
const arr: Uint8Array = LoginRequest.encode(message).finish();
const buffer: ArrayBuffer = arr.buffer;
关于Angular 5 HttpClient 发布原始二进制数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48354712/