Android檔案下載 HttpURLConnection

來源:互聯網
上載者:User

步驟:通過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 }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.