在Android编程上从Internet下载文件

时间:2014-06-09 12:23:03

标签: android httpurlconnection

我是Android编程的新手,我想从互联网上下载文件,但这段代码不起作用。 这是我的包含公共变量的类:

public class G extends Application{
public static Context context;
public static final String             
    SD=Environment.getExternalStorageDirectory().getAbsolutePath();
public static final String SD_path= SD +"/file-downloader";
@Override
public void onCreate() {
    super.onCreate();
    context=this.getApplicationContext();
    new File(SD_path).mkdirs();
}

}

和我的下载程序类:

public class FileDownloader {
public static void download(String address,String Path)
{
    try {
        FileOutputStream output=new FileOutputStream(Path);
        byte[] buffer =new byte[8*1024];
        URL url =new URL(address);
        HttpURLConnection connection =(HttpURLConnection)  
                    url.openConnection();
        connection.setRequestMethod("GET");
        connection.setDoOutput(true);
        connection.connect();



        InputStream stream=connection.getInputStream();
        int len =0;
        while((len=stream.read(buffer))  >0)
        {
            output.write(buffer,0,len);
        }
                    output.close();



    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

}

我的主要课程:

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    FileDownloader.download("http://192.168.1.2/file-server/image1.jpg", 
            G.SD_path+"/img2.jpg");
}

一切都很好,但我不知道为什么这个代码不起作用! 添加到清单和wamp服务器的所有权限都可以正常工作,但会发生错误 ==> Connection.connect(); < ==线。 感谢您的帮助

我的Logcat错误:

06-09 17:00:09.665: E/AndroidRuntime(793): java.lang.RuntimeException: Unable to start     
activity ComponentInfo{com.test.download/com.test.download.MainActivity}:  
android.os.NetworkOnMainThreadException

06-09 17:00:09.665: E/AndroidRuntime(793):  at   
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)

06-09 17:00:09.665: E/AndroidRuntime(793):  at  
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)

06-09 17:00:09.665: E/AndroidRuntime(793):  at 
com.test.download.FileDownloader.download(FileDownloader.java:23)

06-09 17:00:09.665: E/AndroidRuntime(793):  at    
com.test.download.MainActivity.onCreate(MainActivity.java:15)

1 个答案:

答案 0 :(得分:0)

您正在尝试UI线程上的网络连接。请尝试AsyncTask下载。