我点击按钮时想下载整个网页

时间:2014-07-12 12:47:20

标签: android file url save

这是我的代码,它只能保存html但是当我点击按钮我的应用程序崩溃..!我的问题是

  • 当我点击按钮时,我的应用程序崩溃了......为什么?
  • 无论如何,我可以保存完整的网页以供离线观看PLZ帮助

            public void onClick(View view) {
                        download();         
        }
    });
            }
            public void download()
            {
        try {
    //set the download URL, a url that points to a file on the internet
    //this is the file to be downloaded
    URL url = new URL("http://somewhere.com");
    //create the new connection
    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
    //set up some things on the connection
    urlConnection.setRequestMethod("GET");
    urlConnection.setDoOutput(true);
        urlConnection.connect();`
    
    //set the path where we want to save the file
    //in this case, going to save it on the root directory of the
    //sd card.
    File SDCardRoot = new File(Environment.getDataDirectory().getPath());
    //create a new file, specifying the path, and the filename
    //which we want to save the file as.
    File file = new File(SDCardRoot,"somefile.txt");
    
    //this will be used to write the downloaded data into the file we created
    FileOutputStream fileOutput = new FileOutputStream(file);
    
    //this will be used in reading the data from the internet
    InputStream inputStream = urlConnection.getInputStream();
    
    //this is the total size of the file
    int totalSize = urlConnection.getContentLength();
    //variable to store total downloaded bytes
    int downloadedSize = 0;
    //create a buffer...
    byte[] buffer = new byte[1024];
    int bufferLength = 0; //used to store a temporary size of the buffer*emphasized text*
    //now, read through the input buffer and write the contents to the file
    while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
        //add the data in the buffer to the file in the file output stream (the file on the sd card
        fileOutput.write(buffer, 0, bufferLength);
        //add up the size so we know how much is downloaded
        downloadedSize += bufferLength;
        //this is where you would do something to report the prgress, like this maybe
        //updateProgress(downloadedSize, totalSize);
    
    }
    //close the output stream when done
    fileOutput.close();
    

    //抓住一些可能的错误...... } catch(MalformedURLException e){     e.printStackTrace(); } catch(IOException e){     e.printStackTrace(); }

记录猫:

07-13 13:16:33.174: I/Choreographer(791): Skipped 51 frames!  The application may be doing too much work on its main thread.
07-13 13:16:33.274: D/gralloc_goldfish(791): Emulator without GPU emulation detected.
07-13 13:16:33.405: I/Choreographer(791): Skipped 40 frames!  The application may be doing too much work on its main thread.
07-12 12:14:40.053: D/AndroidRuntime(791): Shutting down VM
07-12 12:14:40.053: W/dalvikvm(791): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
07-12 12:14:40.083: E/AndroidRuntime(791): FATAL EXCEPTION: main
07-12 12:14:40.083: E/AndroidRuntime(791): android.os.NetworkOnMainThreadException
07-12 12:14:40.083: E/AndroidRuntime(791):  at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
07-12 12:14:40.083: E/AndroidRuntime(791):  at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
07-12 12:14:40.083: E/AndroidRuntime(791):  at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
07-12 12:14:40.083: E/AndroidRuntime(791):  at java.net.InetAddress.getAllByName(InetAddress.java:214)
07-12 12:14:40.083: E/AndroidRuntime(791):  at libcore.net.http.HttpConnection.<init>(HttpConnection.java:70)
07-12 12:14:40.083: E/AndroidRuntime(791):  at libcore.net.http.HttpConnection.<init>(HttpConnection.java:50)
07-12 12:14:40.083: E/AndroidRuntime(791):  at libcore.net.http.HttpConnection$Address.connect(HttpConnection.java:340)
07-12 12:14:40.083: E/AndroidRuntime(791):  at libcore.net.http.HttpConnectionPool.get(HttpConnectionPool.java:87)
07-12 12:14:40.083: E/AndroidRuntime(791):  at libcore.net.http.HttpConnection.connect(HttpConnection.java:128)
07-12 12:14:40.083: E/AndroidRuntime(791):  at libcore.net.http.HttpEngine.openSocketConnection(HttpEngine.java:316)
07-12 12:14:40.083: E/AndroidRuntime(791):  at libcore.net.http.HttpEngine.connect(HttpEngine.java:311)
07-12 12:14:40.083: E/AndroidRuntime(791):  at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:290)
07-12 12:14:40.083: E/AndroidRuntime(791):  at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:240)
07-12 12:14:40.083: E/AndroidRuntime(791):  at libcore.net.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:81)
07-12 12:14:40.083: E/AndroidRuntime(791):  at com.breeze.http.MainActivity.download(MainActivity.java:54)
07-12 12:14:40.083: E/AndroidRuntime(791):  at com.breeze.http.MainActivity$1.onClick(MainActivity.java:33)
07-12 12:14:40.083: E/AndroidRuntime(791):  at android.view.View.performClick(View.java:4204)
07-12 12:14:40.083: E/AndroidRuntime(791):  at android.view.View$PerformClick.run(View.java:17355)
07-12 12:14:40.083: E/AndroidRuntime(791):  at android.os.Handler.handleCallback(Handler.java:725)
07-12 12:14:40.083: E/AndroidRuntime(791):  at android.os.Handler.dispatchMessage(Handler.java:92)
07-12 12:14:40.083: E/AndroidRuntime(791):  at android.os.Looper.loop(Looper.java:137)
07-12 12:14:40.083: E/AndroidRuntime(791):  at android.app.ActivityThread.main(ActivityThread.java:5041)
07-12 12:14:40.083: E/AndroidRuntime(791):  at java.lang.reflect.Method.invokeNative(Native Method)
07-12 12:14:40.083: E/AndroidRuntime(791):  at java.lang.reflect.Method.invoke(Method.java:511)
07-12 12:14:40.083: E/AndroidRuntime(791):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
07-12 12:14:40.083: E/AndroidRuntime(791):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
07-12 12:14:40.083: E/AndroidRuntime(791):  at dalvik.system.NativeStart.main(Native Method)

1 个答案:

答案 0 :(得分:0)

您正在主ui线程上执行网络请求,这是不允许的。使用AsyncTask。

至于为什么Android阻止这个:你试图通过点击按钮从互联网上下载一些html内容。但是如果你在主线程上执行了整个过程,那么在网络请求完成之前,ui将无法响应(例如按钮将不起作用)。

这有一个很好的示例代码可供使用:http://developer.android.com/reference/android/os/AsyncTask.html

编辑1:

关于如何下载html页面的来源:

HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(url); //Replace url with your own url. 
HttpResponse response = client.execute(request);

String html = "";
InputStream in = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder str = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null) {
    str.append(line);
}
in.close();
html = str.toString();