2014-09-24 85 views
0

这里的多个大尺寸在消息模式单一codeInputStream:>协议缓冲无法解析具有消息

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; 
} 

下面是用于获取从服务响应并调用原应答的方法的代码。

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; 
} 

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

由于

+0

请花费更多的精力来设置您的帖子格式。由于缺少缩进和随机空白行,因此您的代码目前很难阅读。 – 2014-09-24 06:14:02

回答

0

不是将httpresponse转换为字符串,然后转换为字节数组进行解析,而是直接使用EntityUtils.toByteArray。

private String readResponse(HttpResponse httpresponse) throws IOException { 
     int responseCode = httpresponse.getStatusLine().getStatusCode(); 
     String mimeType = httpresponse.getFirstHeader(CONTENT_TYPE_KEY).getValue(); 
     if (responseCode != HttpURLConnection.HTTP_OK) { 
      String cause = String.format("Bad HTTP response code: %d\nOr MIME type: %s", responseCode, mimeType); 
      throw new IOException(cause); 
     } 
     return EntityUtils.toString(httpresponse.getEntity()); 
    } 
+0

像魅力一样工作。谢谢... – Change 2014-09-24 11:02:18

1

这几乎可以肯定是问题:

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

协议缓冲区中的消息是二进制数据。他们不是文字,不应该作为文字处理。你从服务器获取二进制响应,以某种方式将其解释为文本(我们不知道如何),然后使用平台默认编码将其转换回字节数组(这几乎总是一个糟糕的主意 - 从不 - 即使拨打getBytes()合适,它不在此处),请拨打getBytes(),但不指定字符集。转换为文本和后面几乎肯定会丢失信息 - 很可能使解析代码期望比消息中实际存在更多的数据。

你应该处理服务器响应,从一开始的二进制数据 - 理想刚好路过的InputStream来自服务器的响应为parseFrom,但至少阅读它作为一个字节数组,而不是String