[英]Android is not reading full HttpURLConnection InputStream content
I have the following code that has been tested in Java application class and it WORKS It calls my backend Java servlet and read binary bytes into byte[] 我已经在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;
}
Now I move this Java code into My Android code, and somehow it only reads the content partially, the server sends roughly 5709 bytes and Android app only reads 1448 bytes 现在我将这个Java代码移动到我的Android代码中,并且它以某种方式仅部分读取内容,服务器发送大约5709个字节,Android应用程序仅读取1448个字节
The interesting thing is if I go debug mode and put breakpoint at line 有趣的是,如果我进入调试模式并将断点放在一线
int readCount = bufferedInputStream.read(buffer, 0 , contentLength);
And do step by step debug, variable 并逐步调试,变量
readCount
readCount
can reach 5709 bytes. 可以达到5709个字节。 If I didn't put break point, it becomes 1448 bytes.
如果我没有设置断点,则变为1448字节。 Why?
为什么?
It looks like some time delay issue? 看起来有些延时问题?
Thanks. 谢谢。 Regards,
问候,
This works for me : 这对我有用:
// 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();
Thanks everyone's help, especially user greenapps's answer. 感谢大家的帮助,特别是用户greenapps的回答。 I break the load process into 1kb buffer and resolved the problem.
我将加载过程分解为1kb缓冲区并解决了问题。 The following is the code:
以下是代码:
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.