安卓:错误从网上下载的文本文件 [英] Android: error downloading text file from the web

查看:132
本文介绍了安卓:错误从网上下载的文本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有4个选项卡,一个是更新来自网络的输入文本文件并将其写入SD卡的应用程序。我的code执行,因为尝试catch块,但跟踪显示连接错误。该文件被写入到SD卡上,但它是0字节。因此,文件写入是好的,但我觉得有HHTP连接问题。我使用Windows 7 64位与最新的SDK。

I have an app with 4 tabs, one being to update an input text file from the web and write it to the sd card. My code executes because of try catch blocks, but the trace shows connection errors. The file gets written to the sd card, but it is 0 bytes. So the file writing is good, but I think there's hhtp connection problems. I'm using Windows 7 64 bit with the latest sdk.

下面是我的code:

    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的输出:

Here's the logcat output:

    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文件:

Here's my Manifest.xml file:

    <?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>

任何帮助或建议将是AP preciated。先谢谢了。

Any help or suggestions would be appreciated. Thanks in advance.

推荐答案

的Andr​​oid抛出异常。
的AsyncTask 打电话给你的 downloadFile 方法。这将解决这个问题。

Android throws an exception when you try to do network related operations on the main thread. Call your downloadFile method from an AsyncTask. It will solve the problem.

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

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

您可以然后使用下面code下载的文件。

You could then download the file using the below code.

new FileDownloadTask().execute(url);

这篇关于安卓:错误从网上下载的文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆