我有以下代码已经在Java应用程序类中测试过并且 WORKS 它调用我的后端Java servlet并将二进制字节读入byte []
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字节。 为什么呢?
看起来有些延时问题?
感谢。 的问候,
答案 0 :(得分:0)
这对我有用:
// 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();
答案 1 :(得分:0)
感谢大家的帮助,尤其是用户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;
}