tags:

views:

103

answers:

2

Hi guys.

I am facing with problem related Http Connection. MY code :

URL url = null;
try {
    url = new URL(_url);
} catch (MalformedURLException e) {
}

if (url != null) {
    HttpURLConnection urlConn = null;
    InputStreamReader isr = null;
    try {
        urlConn = (HttpURLConnection)url.openConnection();
        urlConn.setRequestMethod("GET");
        urlConn.setConnectTimeout(45000);

        if(response == HttpURLConnection.HTTP_OK) {
            StringBuffer readData = new StringBuffer("");
            int size = 1024;
            char[] buffer = new char[size];
            int len;
            isr = new InputStreamReader(urlConn.getInputStream());
            while ((len = isr.read(buffer, 0, size)) > 0) {
                readData.append(buffer, 0, len);
            }
        }
    } 
    catch(Exception e) {
    } 
    finally {
        if(urlConn != null) {

        try {
            urlConn.disconnect();
        } catch(Exception e) {            
        }
    }
    if(isr != null) {
        try {
           isr.close();
        } catch(Exception e) {                
        }            
    }
}

This code can't download data completely. For example : Total size to read : 13901 bytes Above code can read size : 12937 bytes

What is wrong here ?

Please advice guys.

+2  A: 

Hi!
I've checked your code and it seems to be OK. But you have to bear in mind that you are reading chars (2 bytes type) - so your readData.length() will show number of characters, not bytes. I made a test and changed your InputStreamReader to BufferedInputStream and type of buffer to byte[]. The code read exactly the number of bytes I expected.
Regads!

Ramps
While the underlying point about character conversion is valid, your comment on character taking 2 bytes is not generally correct -- only UTF-16/UCS-2 has fixed 2-bytes-per-char encoding, and they are not commonly used by web servers. UTF-8 is a variable length encoding (1 - 3 bytes per Java char); Latin-1 is fixed 1-byte per char and so on.
StaxMan
A: 

Also to add to the accepted answer: I would consider code buggy because it does not specify what character encoding InputStreamReader is to use -- it's the platform default, which may different from what the resource is using. So always either specify encoding to use explicitly ("UTF-8"), or use a library that does this.

StaxMan