Android文件下载 HttpURLConnection

步骤:通过new URL(目标网址字符串)得到URL对象url---->调用url的openConnection方法获得一个HttpURLConnection对象connection---->调用connection的getInputStream方法获得一个InputStream对象,访问结束,接下来就是io操作了。

实例:              

 16 public class DownloadDemoActivity extends Activity {
 17     /** Called when the activity is first created. */
 18     TextView textView;
 19 
 20     Handler handler = new Handler(){
 21 
 22         @Override
 23         public void handleMessage(Message msg)
 24         {
 25             textView.setText((String)msg.obj);
 26         }
 27 
 28     };
 29 
 30 
 31     @Override
 32     public void onCreate(Bundle savedInstanceState) {
 33         super.onCreate(savedInstanceState);
 34         setContentView(R.layout.main);
 35 
 36         textView = (TextView) findViewById(R.id.textView1);
 37 
 38     }

 39 
 40     public void buttonClick(View view)
 41     {
 42         new Thread(){
 43 
 44             @Override
 45             public void run()
 46             {
 47                 StringBuffer stringBuffer = new StringBuffer();
 48                 HttpURLConnection connection = null;
 49 
 50                 try
 51                 {
 52                     URL url = new URL("http://www.baidu.com");
 53                     connection =
 54                         (HttpURLConnection) url.openConnection();
 55 
 56                     BufferedReader bReader = new BufferedReader
 57                         (new InputStreamReader(connection.getInputStream()))    ;
 58                     String str;
 59 
 60                     while((str = bReader.readLine() ) != null)
  61                     {
 62                         stringBuffer.append(str);
 63                     }
 64 
 65                 }
 66                 catch (Exception e)
 67                 {
 68                     // TODO Auto-generated catch block
 69                     e.printStackTrace();
 70                 }finally{
 71                     connection.disconnect();
 72                 }
 73 
 74                 Message msg = handler.obtainMessage();
 75                 msg.obj = stringBuffer.toString();
 76                 msg.sendToTarget();
 77 
 78             }
 79 
 80 
 81 
 82         }.start();
 83     }

 84 }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值