如何调整代码以下载完整大小的内容?

时间:2015-06-20 06:09:02

标签: android

如何下​​载完整尺寸的内容。我遵循了android Connecting to the Network教程,他们提到了int len = 500;它只下载了500个字符我的Api返回的字符多于字符。那么如何调整代码来下载完整内容呢?

以下是目前正在使用的代码......

private String downloadUrl(String myurl) throws IOException {
    InputStream is = null;
    // Only display the first 500 characters of the retrieved
    // web page content.
    int len = 500;

    try {
        URL url = new URL(myurl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(10000 /* milliseconds */);
        conn.setConnectTimeout(15000 /* milliseconds */);
        conn.setRequestMethod("GET");
        conn.setDoInput(true);
        // Starts the query
        conn.connect();
        int response = conn.getResponseCode();
        is = conn.getInputStream();

        // Convert the InputStream into a string
        String contentAsString = readIt(is, len);
        return contentAsString;

        // Makes sure that the InputStream is closed after the app is
        // finished using it.
    } finally {
        if (is != null) {
            is.close();
        }
    }
}
// Reads an InputStream and converts it to a String.
public String readIt(InputStream stream, int len) throws IOException, UnsupportedEncodingException {
    Reader reader = null;
    reader = new InputStreamReader(stream, "UTF-8");
    char[] buffer = new char[len];
    reader.read(buffer);
    return new String(buffer);
}

我事件尝试将len值增加到5000并且也遇到同样的问题。

1 个答案:

答案 0 :(得分:0)

您可以尝试此操作,而不是public String readIt

BufferedReader r = new BufferedReader(new InputStreamReader(is));
StringBuilder total = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
       total.append(line);
}
String resultString = total.toString()