简体   繁体   中英

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

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

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

can reach 5709 bytes. If I didn't put break point, it becomes 1448 bytes. 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. I break the load process into 1kb buffer and resolved the problem. 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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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