1. 程式人生 > >Android通過URL獲取網路資料

Android通過URL獲取網路資料

 本例項主要是通過URL獲取網路資源,在具體一點,就是簡單介紹如何獲取網頁文字資源。獲取網路資源還有獲取圖片、視訊、音訊……資源,框架基本相似。

實驗時出現兩點小問題:1、丟擲Connection Refused的異常;

                                             2、出現亂碼。

解決辦法:1、由於我用的是本地伺服器,就不假思索的以為和WEB的實驗一樣,只要輸入http://localhost:8080/就可以得到實驗結果,結果錯誤,要用網路伺服器地址。

                    2、  myString = new String(baf.toByteArray(), "GBK");

                             //myString = EncodingUtils.getString(baf.toByteArray(), "GBK");                              //myString = new String(baf.toByteArray());這個出現亂碼,要在txt檔案儲存時選中utf-8                            這三種任選一種。 當然,設定使用者許可權這個就不用說了! Code:
  1. package com.web.test;  
  2. import java.io.BufferedInputStream;  
  3. import java.io.InputStream;  
  4. import java.net.URL;  
  5. import java.net.URLConnection;  
  6. import org.apache.http.util.ByteArrayBuffer;  
  7. import org.apache.http.util.EncodingUtils;  
  8. import android.app.Activity;  
  9. import android.os.Bundle;  
  10. import android.widget.TextView;  
  11. /* 
  12.  * 獲取網路資料,這裡展示如何獲取網路上的一個poem.txt文字檔案,架設了一個本地伺服器
     
  13.  */
  14. publicclass HelloWeb extends Activity {  
  15.     /** Called when the activity is first created. */
  16.     @Override
  17.     publicvoid onCreate(Bundle savedInstanceState) {  
  18.         super.onCreate(savedInstanceState);  
  19.         setContentView(R.layout.main);  
  20.         TextView tv = new TextView(this);  
  21.         String myString = null;  
  22.         try {  
  23.             URL uri = new URL("http://172.16.194.157:8080/my/my.txt");//注意,這裡的URL地址必須為網路地址,  
  24.             //URL uri = new URL("http://localhost:8080/my/poem.txt");
  25.             //本地地址http://localhost:8080/my/poem.txt會報Connection Refused的異常
  26.             URLConnection ucon = uri.openConnection();  
  27.             InputStream is = ucon.getInputStream();  
  28.             BufferedInputStream bis = new BufferedInputStream(is);  
  29.             ByteArrayBuffer baf = new ByteArrayBuffer(100);  
  30.             int current = 0;  
  31.             while((current = bis.read()) != -1) {  
  32.                 baf.append((byte)current);  
  33.             }  
  34.             myString = new String(baf.toByteArray(), "GBK");  
  35.             //myString = EncodingUtils.getString(baf.toByteArray(), "GBK");
  36.             //myString = new String(baf.toByteArray());這個出現亂碼,要在txt檔案儲存時選中utf-8
  37.         } catch(Exception e) {  
  38.             myString = e.getMessage();  
  39.         }  
  40.         tv.setText(myString);  
  41.         this.setContentView(tv);  
  42.     }  
  43. }  
修改txt文字檔案的編碼格式 出現異常 執行成功之後