这是消息架构:>
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/