Android:从网上下载文本文件时出错

时间:2013-06-06 12:33:17

标签: android

我有一个带有4个标签的应用程序,一个用于从网络更新输入文本文件并将其写入SD卡。我的代码由于try catch块而执行,但跟踪显示连接错误。该文件被写入sd卡,但它是0字节。所以文件编写很好,但我认为有hhtp连接问题。我正在使用Windows 7 64位和最新的sdk。

这是我的代码:

    public void downloadFile (String urlfile) throws IllegalStateException, IOException
    {

    InputStream instream = null;
    String result = null;


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


     HttpClient httpclient = new DefaultHttpClient();

     // Prepare a request object
      HttpGet httpget = new HttpGet(urlfile); 

     // Execute the request
      HttpResponse response;

      File file = new File(Environment.getExternalStorageDirectory(), "myfile.txt");    

      FileOutputStream fileOutput = new FileOutputStream(file);

              OutputStreamWriter myOutWriter = new OutputStreamWriter(
                    fileOutput);

      try {
           response = httpclient.execute(httpget);

           // Examine the response status
           Log.i("Praeda",response.getStatusLine().toString());

           // Get hold of the response entity
               HttpEntity entity = response.getEntity();

           // If the response does not enclose an entity, there is no need
           // to worry about connection release

           if (entity != null) {

                // A Simple JSON Response Read
                instream = entity.getContent();
                result= convertStreamToString(instream);

                 // now you have the string representation of the HTML request


            }

            myOutWriter.write(result);
            instream.close();
            myOutWriter.close();
                fileOutput.close();

            //catch some possible errors...


            } catch (Exception e) {
                  e.printStackTrace();
        } finally {

        }


    //catch some possible errors...

    } catch (Exception e)  {
         e.printStackTrace();
    } finally  {
    }

}


    private static String convertStreamToString(InputStream is)
    {
    /*
     * To convert the InputStream to String we use the BufferedReader.readLine()
     * method. We iterate until the BufferedReader return null which means
     * there's no more data to read. Each line will appended to a StringBuilder
     * and returned as String.
    */

        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();

        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            } 
        } catch (IOException e) {
                e.printStackTrace();
        } finally {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }
        return sb.toString();

    }

这是logcat输出:

    W/ActivityManager(278): Unbind failed: could not find connection for android.os.BinderProxy@40f82428


    W/System.err(720): android.os.NetworkOnMainThreadException
    W/System.err(720): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
    W/System.err(720): at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
    W/System.err(720): at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
    W/System.err(720): at java.net.InetAddress.getAllByName(InetAddress.java:214)
    W/System.err(720): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
    W/System.err(720): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
    W/System.err(720): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
    W/System.err(720): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
    W/System.err(720): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
    W/System.err(720): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
    W/System.err(720): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
    W/System.err(720): at com.gmail.tenglish7.lae.MainActivity$UpdateFragment.downloadFile(MainActivity.java:506)
    W/System.err(720): at com.gmail.tenglish7.lae.MainActivity$UpdateFragment.myClick(MainActivity.java:466)
    W/System.err(720): at com.gmail.tenglish7.lae.MainActivity$UpdateFragment$1.onClick(MainActivity.java:448)
    W/System.err(720): at android.view.View.performClick(View.java:4204)
    W/System.err(720): at android.view.View$PerformClick.run(View.java:17355)
    W/System.err(720): at android.os.Handler.handleCallback(Handler.java:725)
    W/System.err(720): at android.os.Handler.dispatchMessage(Handler.java:92)
    W/System.err(720): at android.os.Looper.loop(Looper.java:137)
    W/System.err(720): at android.app.ActivityThread.main(ActivityThread.java:5041)
    W/System.err(720): at java.lang.reflect.Method.invokeNative(Native Method)
    W/System.err(720): at java.lang.reflect.Method.invoke(Method.java:511)
    W/System.err(720): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
    W/System.err(720): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
    W/System.err(720): at dalvik.system.NativeStart.main(Native Method)

这是我的Manifest.xml文件:

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.gmail.tenglish7.lae"
        android:versionCode="1"
        android:versionName="1.0" >

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

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

        <uses-sdk
            android:minSdkVersion="14"
            android:targetSdkVersion="17" />



        <application
            android:allowBackup="true"
            android:icon="@drawable/ic_launcher"
            android:label="@string/app_name"
            android:theme="@style/AppTheme" >
            <activity
                android:name="com.gmail.tenglish7.lae.MainActivity"
                android:label="@string/app_name" >
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />

                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
         </application>

    </manifest>

任何帮助或建议将不胜感激。提前谢谢。

1 个答案:

答案 0 :(得分:1)

当您尝试在主线程上执行与网络相关的操作时,Android会抛出异常。 从downloadFile调用AsyncTask方法。它将解决问题。

class FileDownloadTask extends AsyncTask<String, Void, Void>{

    @Override
    protected Void doInBackground(String... params) {
        downloadFile(params[0]);
        return null;
    }
}

然后,您可以使用以下代码下载该文件。

new FileDownloadTask().execute(url);