Android开发实例教程1之下载网络资源

使用HttpURLConnection与URL对应的服务器建立连接

package com.example.androidtest1;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
    private EditText et_path;
    private Button bt;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
                  
        et_path = (EditText)findViewById(R.id.editText1);
        bt = (Button)findViewById(R.id.button1);
        bt.setOnClickListener(new OnClickListener(){
            @Override
            public void onClick(View v) {
                //String path = "http://192.168.1.25:8080/ServerForPicture/lv.jpg";
                String path = et_path.getText().toString();
                getImgWithURL(path);
            }
        });
    }
              
    Handler handler = new Handler()
    {
        @Override
        public void handleMessage(Message msg)
        {
            Log.i("debug", "=====> Getting message...");
            super.handleMessage(msg);
            if(msg.what == 101){
                String info = "Failed to download -_-||";
                Toast.makeText(MainActivity.this, info, Toast.LENGTH_LONG).show();
            }
            else if(msg.what == 100)
            {
                String info = "Downloaded completely ^_^";
                Toast.makeText(MainActivity.this, info, Toast.LENGTH_LONG).show();
            }
        }
    };
              
    private void getImgWithURL(String path)
    {
        class MyThread extends Thread
        {
            public String path;
            public void run()
            {
                Message msg = new Message();
                try {
                    //实例化URL
                    URL url = new URL(path);
                    HttpURLConnection conn = (HttpURLConnection)url.openConnection();
                    conn.setConnectTimeout(50*1000);
                    if(conn.getResponseCode()!=HttpURLConnection.HTTP_OK)
                        throw new Exception("连接不成功");
                    Log.i("debug", "=====> connected!");
                              
                    //获得输入流
                    InputStream is = conn.getInputStream();
                              
                    String fileName = path.substring(path.lastIndexOf("/")+1);
                    float fileSize = conn.getContentLength();
                    //记录已下载长度
                    float temp = 0;
                    int len = 0;
                    byte buffer[] = new byte[1024*4];
                              
                    //Environment.getExternalStorageDirectory()获得SD卡的根目录
                    File file = new File(Environment.getExternalStorageDirectory()+"/MyFile");
                    //创建新目录
                    if(file.mkdir())
                        Log.i("info", "===>File direction is created");
                    else{
                        Log.i("info", "===>File diretion can't be created");
                        throw new Exception("File diretion can't be created");
                    }
                    //创建文件输出流
                    FileOutputStream fos = new FileOutputStream(file.getPath()+"/"+fileName);
                              
                    while((len=is.read(buffer))!=-1)
                    {
                        //将字节写入文件输出流
                        fos.write(buffer,0,len);
                        temp += len;
                        Log.i("progress", "finished===>"+temp/fileSize * 100 + "%");
                    }
                    Log.i("progress", "Done!!!");
                    fos.flush();
                    fos.close();
                    is.close();
                    msg.what = 100;
                } catch (Exception e) {
                    e.printStackTrace();
                    Log.i("debug", "=====> Exception when downloading");
                    msg.what = 101;
                }
                handler.sendMessage(msg);
            }
        }
                  
        MyThread thread = new MyThread();
        thread.path = path;
        thread.start();
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
}


因为要使用网络和SD卡,必须在AndroidManifest.xml文件中加入权限说明:

你可能感兴趣的:(android,网络编程)