StringBuffer无法完全读取

时间:2012-04-11 10:56:06

标签: java string stringbuffer

我有一个简单的功能,用于连接服务器并将响应作为字符串返回。当返回的数据大小很小但响应很大时,它工作正常。它不完全存储服务器返回的响应字符串,并以...结束字符串。 令人惊讶的是,system.out.println返回正确的响应。请帮帮我。我真的被卡住了。

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();
}

2 个答案:

答案 0 :(得分:2)

(编辑:此答案基于OP最初发布的代码。此后OP已编辑该问题以更改有问题的代码。)

这里有一个错误:

sb.append(line.trim(), 0, line.length());

如果line有任何前导或尾随空格,line.length()将大于line.trim().length()。在这种情况下sb.append() would throw IndexOutOfBoundsException

  

IndexOutOfBoundsException - 如果startend为否定,或start大于end end大于s.length()

答案 1 :(得分:0)

您在调试时是否收到了截断的字符串(以...结尾)?试试System.out.println(sb.toString());在你回来之前。