【问题标题】:What is the right way to encode a protobuf serializeBinary response to send it over http post body?编码 protobuf serializeBinary 响应以通过 http post body 发送它的正确方法是什么?
【发布时间】:2019-05-16 01:31:04
【问题描述】:

我正在尝试通过 http post 从 node js 客户端向 java spring 服务器发送一个 protobuf。

message.serializeBinary() 给了我一个 uint8 字节数组,我尝试用new StringDecoder('utf8').write(<bytes>) 对其进行编码。然后我通过 npm request-promise 发送它:

 const request = require('request-promise')
 const options = {
  uri: <some url>,
  method: 'POST',
  qs: {
    'attr1': 'value1',
    'attr2': new StringDecoder('utf8').write(message.serializeBinary())
  }
}
request(options).then(console.log).catch(console.log)

这会命中 spring 服务器端点

@ResponseBody String endpoint(@RequestParam String attr1, @RequestParam String attr2) {
  // This is raising InvalidProtocolBufferException
  var message = Message.parseFrom(attr2.getBytes(StandardCharsets.UTF_8));  
}

对我来说似乎是编码问题,我不确定使用什么编码来通过 http 传输协议缓冲区。或者如果我做错了什么,也请指出。

【问题讨论】:

  • 您好,先生,我也遇到了和您一样的错误。你是怎么解决的?
  • 问题是在查询字符串中发送它,它根据 url 长度限制被截断,我开始将它作为表单数据传递并修复它。
  • 如果您确保将记录保存在较小的一侧,Base64 编码 protobuf 应该也可以工作

标签: node.js spring encoding utf-8 http-post


【解决方案1】:

tl;dr 解决方法是将 qs 改为 form

const options = {
  uri: <some url>,
  method: 'POST',
  form: {
    'attr1': 'value1',
    'attr2': new StringDecoder('utf8').write(message.serializeBinary())
  }
}

问题是将编码的 protobuf 作为查询字符串参数传递,它是 url 的一部分。 Url 有基于浏览器的可变长度限制,最好将其作为表单数据传递。见What is the maximum length of a URL in different browsers?

【讨论】:

    猜你喜欢
    • 2018-01-12
    • 2017-10-21
    • 1970-01-01
    • 2010-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-09
    相关资源
    最近更新 更多