Angular 5 HttpClient发布原始二进制数据 [英] Angular 5 HttpClient post raw binary data

查看:73
本文介绍了Angular 5 HttpClient发布原始二进制数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的WebApp需要通过ProtBuf与我的服务器通信.为此,我需要能够发布原始二进制数据.

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.

这是我现在正在使用的代码.问题在于 HttpClient 将Uint8Array编码为JSON数组,因此结果不再是有效的原型缓冲区:

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 接受一些选项,您可以在其中将 responseType 设置为 json text blob arraybuffer .但这只是设置了预期的响应类型,请求的主体仍被编码为JSON.

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.

HttpClient 是否可以发送未编码的正文?

Does HttpClient have the possibility to send unencoded bodies?

这是我在服务器上收到的正文:

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}

推荐答案

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.

它接受许多身体类型,所有这些身体类型都相应地进行了字符串化处理.原始正文应为 Blob ArrayBuffer 或字符串.因此, Uint8Array 应该转换为其中之一,例如:

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;

这篇关于Angular 5 HttpClient发布原始二进制数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆