1 布局
<ScrollView android:layout_width="wrap_content" android:layout_height="wrap_content" > <TextView android:id="@+id/result" android:layout_width="fill_parent" android:layout_height="wrap_content" /></ScrollView>
在ScrollView控制項裡嵌入一個TextView即可,其帶有一個捲軸.
2利用網頁的路徑和編碼方式,得到網頁的位元組數組
public class GetPageResource { public static String getHtml(String path,String encoding) throws Exception{ HttpURLConnection connection=(HttpURLConnection) new URL(path).openConnection(); connection.setConnectTimeout(5000); connection.setRequestMethod("POST"); if(connection.getResponseCode()==200){ InputStream inputStream=connection.getInputStream(); byte [] imageData=GetResource.readResource(inputStream); return new String(imageData,encoding); } return null; }}
分析:
(1)關於網頁的編碼方式,可以利用HttpWatch工具來擷取
(2)利用URL得到HttpURLConnection connection這樣便於資源建立起了聯絡,且設定connection的屬性值
(3)利用HttpURLConnection connection得到輸入資料流.即可以這麼想:此時的網頁已經儲存到了此輸入資料流inputStream裡
(4)將在輸入資料流裡的網頁資料輸出到位元組數組裡面.即byte [] imageData=GetResource.readResource(inputStream).如下
readResource(inputStream)方法如下:
public class GetResource { public static byte[] readResource(InputStream inputStream) throws Exception{ ByteArrayOutputStream outputStream=new ByteArrayOutputStream(); byte [] array=new byte[1024]; int len=0; while( (len=inputStream.read(array))!=-1){ outputStream.write(array,0,len); } inputStream.close(); outputStream.close(); return outputStream.toByteArray(); }
分析:
(1)沒有方法可以把輸入資料流裡的資料直接放到位元組數組裡(查閱API即知),而是要利用ByteArrayOutputStream outputStream
把在輸入資料流自己把自己的資料讀(read())到一個位元組數組裡面,即inputStream.read(buffer),然後數組裡面的資料放入
輸出資料流ByteArrayOutputStream outputStream裡面,即outputStream.write(buffer,0,len);
(2)待資料全部轉移到輸入資料流outputStream裡面,此時就可以把輸出資料流的資料全部轉換為位元組數組,即outputStream.toByteArray();
(3)在此例子就很好體現了輸入資料流和輸出資料流的使用.
在輸入資料流相應的API中都是把輸入資料流讀取到一個數組中,或者唯讀取一個位元組,或者讀取一行
如FileInputStream類中的方法:
public int read(byte[] b,int off,int len)從此輸入資料流中將最多 len 個位元組的資料讀入一個位元組數組中
public int read()從此輸入資料流中讀取一個資料位元組
如在BufferedReader類中的方法:
public String readLine() 讀取一個文本行.傳回值:包含該行內容的字串
在輸出資料流相應的API中都把是位元組數組寫入此輸出資料流,或者只把數組中的某個位置的資料寫入輸出資料流
如ByteArrayOutputStream類的方法中:
public void write(byte[] b,int off,int len)將指定位元組數組中從位移量off開始的len個位元組寫入此位元組數組輸出資料流
public void write(int b)將指定的位元組寫入此位元組數組輸出資料流
然後我們可以發現:
(1)可以把輸出資料流裡的資料轉換為位元組數組
如ByteArrayOutputStream類的方法中:
public byte[] toByteArray():建立一個新分配的位元組數組。其大小是此輸出資料流的當前大小,並且緩衝區的有效內容已複製到該數組中。
(2)可以把輸出資料流裡的資料轉換為字串
如ByteArrayOutputStream類的方法中:
public String toString():將緩衝區的內容轉換為字串,根據平台的預設字元編碼將位元組轉換成字元。