Search code examples
javastringstringbuffer

StringBuffer does not read completely


I have a simple function for connecting to a server and returning the response as a string. It works fine when the size of data returned is small but when the response is large. It does not store the returned response string by the server completely and ends the string with ... Surprisingly the system.out.println returns the correct response. Please help me out. I am really stuck.

protected String getResponseFromServer(String URLaddress) {

    HttpURLConnection connection = null;
    URL serverAddress = null;
    BufferedReader rd = null;
    StringBuffer sb = new StringBuffer();
    try {
        serverAddress = new URL(URLaddress);
        // set up out communications stuff
        connection = null;
        connection = (HttpURLConnection) serverAddress.openConnection();
        connection.setReadTimeout(20000);
        connection.connect();
        // read the result from the server
        rd = new BufferedReader(new InputStreamReader(
                connection.getInputStream()));
        String line;
        while ((line = rd.readLine()) != null) {
            System.out.print(line.trim());
            sb.append(line.trim());
        }

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        // close the connection, set all objects to null
        connection.disconnect();
        connection = null;
    }
    return sb.toString();
}

Solution

  • Are you getting that truncated string (ends with ...) while you debug? Try System.out.println(sb.toString()); before you return.