![](/img/trans.png)
[英]Android HttpUrlConnection InputStream reading error(JSONException: Unterminated array)
[英]Android is not reading full HttpURLConnection InputStream content
我已經在Java應用程序類進行了測試下面的代碼和它的作品 ,它調用我的后端的Java servlet和讀取二進制字節到字節[]
private byte[] readResponse(HttpURLConnection connection) throws IOException {
InputStream inputStream = connection.getInputStream();
BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
int contentLength = connection.getContentLength();
byte[] buffer;
if (contentLength>-1) {
buffer = new byte[contentLength];
int readCount = bufferedInputStream.read(buffer, 0 , contentLength);
System.out.println("Content Length is " + contentLength + " Read Count is " + readCount);
}
return buffer;
}
現在我將這個Java代碼移動到我的Android代碼中,並且它以某種方式僅部分讀取內容,服務器發送大約5709個字節,Android應用程序僅讀取1448個字節
有趣的是,如果我進入調試模式並將斷點放在一線
int readCount = bufferedInputStream.read(buffer, 0 , contentLength);
並逐步調試,變量
readCount
可以達到5709個字節。 如果我沒有設置斷點,則變為1448字節。 為什么?
看起來有些延時問題?
謝謝。 問候,
這對我有用:
// Read response
//int responseCode = connection.getResponseCode();
StringBuilder response = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
response.toString();
感謝大家的幫助,特別是用戶greenapps的回答。 我將加載過程分解為1kb緩沖區並解決了問題。 以下是代碼:
private byte[] readResponse(HttpURLConnection connection) throws IOException {
InputStream inputStream = connection.getInputStream();
int contentLength = connection.getContentLength();
byte[] buffer;
buffer = new byte[contentLength];
int bufferSize = 1024;
int bytesRemaining = contentLength;
int loadedBytes;
for (int i = 0; i < contentLength; i = i + loadedBytes) {
int readCount = bytesRemaining > bufferSize ? bufferSize : bytesRemaining;
loadedBytes = inputStream.read(buffer, i , readCount);
bytesRemaining = bytesRemaining - loadedBytes;
}
return buffer;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.