繁体   English   中英

Android没有读取完整的HttpURLConnection InputStream内容

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM