2014-09-24 35 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

相關問題