Android下载文件错误

时间:2011-08-13 12:50:20

标签: android download

public class Downloader {
    public static String getWebPage(String URLString) {
        String retVal = "";
        try {
            // Perform action on click
            URL url = new URL(URLString);
            URLConnection conn = url.openConnection();
            // Get the response
            BufferedReader rd = new BufferedReader(new InputStreamReader(
                    conn.getInputStream()));
            String line = "";
            while ((line = rd.readLine()) != null) {
                retVal += line + "\n";
            }
            rd.close();
        } catch (MalformedURLException e) {
            // Print out the exception that occurred
            retVal = "Invalid URL " + URLString + ": " + e.getMessage();
        } catch (Exception e) {
            retVal = e.getMessage();
        }
        return retVal;
    }
}

上面的代码在模拟器2.3.1上运行良好。当我尝试在模拟器3.x.x或我的Motorolla XOOM上执行相同操作时,代码不起作用。它不会产生任何错误,但会返回空白文本。知道如何解决这个问题吗?

注意:我在清单文件中包含以下内容。

<uses-permission android:name="android.permission.INTERNET" />

1 个答案:

答案 0 :(得分:0)

  

用这个家伙   公共课下载{

    public static void DownloadFile(String fileURL, File directory) {
            try {

                    FileOutputStream f = new FileOutputStream(directory);
                    URL u = new URL(fileURL);
                    HttpURLConnection c = (HttpURLConnection) u.openConnection();
                    c.setRequestMethod("GET");
                    c.setDoOutput(true);
                    c.connect();

                    InputStream in = c.getInputStream();

                    byte[] buffer = new byte[1024];
                    int len1 = 0;
                    while ((len1 = in.read(buffer)) > 0) {
                            f.write(buffer, 0, len1);
                    }
                    f.close();
            } catch (Exception e) {
                    e.printStackTrace();
            }

    }

}