java - Protocol buffer 无法解析具有多个大尺寸消息的单个 codeInputStream

标签 java android protocol-buffers

这是消息架构:>

message ServerResponse {
optional string ReferenceCode = 1;
optional NestedMessageProto.NestedMessage NestedMessage = 2;//Huge size data in response
optional bool Success = 3 [default = false];
repeated Errors Errors = 4;
}

下面是从服务获取响应并调用原型(prototype)响应方法的代码。

 String apiResponse = Server Response
    protoResponseClass.parseFrom(apiResponse.getBytes())

its failing when reading the NestedMessage  response on below bold line

    public int pushLimit(int byteLimit) throws InvalidProtocolBufferException {
    if (byteLimit < 0) {
        throw InvalidProtocolBufferException.negativeSize();
    }
    byteLimit += totalBytesRetired + bufferPos;
    if (byteLimit > currentLimit) {
        currentLimit = byteLimit + currentLimit;
    }
    final int oldLimit = currentLimit;
    **if (byteLimit > oldLimit) {
        throw InvalidProtocolBufferException.truncatedMessage();
    }**
    currentLimit = byteLimit;
    recomputeBufferSizeAfterLimit();
    return oldLimit;
}

当其读取嵌套消息时,字节限制变得大于旧限制。 解决办法是什么?

谢谢

最佳答案

这几乎肯定是问题所在:

String apiResponse = Server Response
protoResponseClass.parseFrom(apiResponse.getBytes())

Protocol Buffer 消息是二进制数据。它们不是文本,也不应作为文本处理。您从服务器获取二进制响应,以某种方式将其解释为文本(我们不知道如何),然后使用平台默认编码将其转换回字节数组(这几乎总是一个坏主意 - 永远不要调用 getBytes() 而不指定字符集,即使调用 getBytes() 是合适的,但它不在这里)。文本和文本的转换几乎肯定会丢失信息 - 很可能使解析代码期望比消息中实际存在的数据更多的数据。

您应该从一开始就将服务器响应作为二进制数据处理 - 理想情况下只需将服务器响应中的 InputStream 传递到 parseFrom 中,但至少 将其读取为字节数组而不是 String

关于java - Protocol buffer 无法解析具有多个大尺寸消息的单个 codeInputStream,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26009692/

相关文章:

ios - 如何为 protobuf 生成 swift 文件

protocol-buffers - 如何包含具有相互依赖性的 .proto 文件

java - java应用程序中所有级别url的主页按钮

java - 支持多种类型操作的客户端套接字和服务器套接字之间通信的最佳方式是什么?

java - 在使用 Java 启动应用程序之前检测 Play 2.2.x 模式

android - Google Play 控制台不会减少应用程序下载大小

windows - Windows 上运行的 C# 与 linux 上运行的 C 通过 protobuf 进行通信

java - 从带有两个参数的方法创建新数组java

java - 以编程方式减少处理程序中的时间间隔。安卓

android - 用于 React Native Android 的 XMPP 库