0

我有一个简单的函数用于连接服务器并将响应作为字符串返回。当返回的数据量很小但响应很大时,它可以正常工作。它不会完全存储服务器返回的响应字符串,并以...结束字符串。令人惊讶的是,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();
}
4

2 回答 2

2

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

一个错误在这里:

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

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

IndexOutOfBoundsException- 如果startorend是负数, orstart大于endend大于s.length()

于 2012-04-11T11:00:57.623 回答
0

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

于 2012-04-11T11:28:37.727 回答