我有以下代码,已在 Java 应用程序类中进行了测试,并且它有效 它调用我的后端 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 字节
有趣的是,如果我进入 Debug模式并在行上放置断点
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();
关于java - Android 未读取完整的 HttpURLConnection InputStream 内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42732421/