Android通過URL獲取網路資料
阿新 • • 發佈:2019-01-01
本例項主要是通過URL獲取網路資源,在具體一點,就是簡單介紹如何獲取網頁文字資源。獲取網路資源還有獲取圖片、視訊、音訊……資源,框架基本相似。
實驗時出現兩點小問題:1、丟擲Connection Refused的異常;
2、出現亂碼。
解決辦法:1、由於我用的是本地伺服器,就不假思索的以為和WEB的實驗一樣,只要輸入http://localhost:8080/就可以得到實驗結果,結果錯誤,要用網路伺服器地址。
2、 myString = new String(baf.toByteArray(), "GBK");
- package com.web.test;
-
import java.io.BufferedInputStream;
- import java.io.InputStream;
- import java.net.URL;
- import java.net.URLConnection;
- import org.apache.http.util.ByteArrayBuffer;
- import org.apache.http.util.EncodingUtils;
- import android.app.Activity;
- import android.os.Bundle;
- import android.widget.TextView;
- /*
-
* 獲取網路資料,這裡展示如何獲取網路上的一個poem.txt文字檔案,架設了一個本地伺服器
- */
- publicclass HelloWeb extends Activity {
- /** Called when the activity is first created. */
- @Override
- publicvoid onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- TextView tv = new TextView(this);
- String myString = null;
- try {
- URL uri = new URL("http://172.16.194.157:8080/my/my.txt");//注意,這裡的URL地址必須為網路地址,
- //URL uri = new URL("http://localhost:8080/my/poem.txt");
- //本地地址http://localhost:8080/my/poem.txt會報Connection Refused的異常
- URLConnection ucon = uri.openConnection();
- InputStream is = ucon.getInputStream();
- BufferedInputStream bis = new BufferedInputStream(is);
- ByteArrayBuffer baf = new ByteArrayBuffer(100);
- int current = 0;
- while((current = bis.read()) != -1) {
- baf.append((byte)current);
- }
- myString = new String(baf.toByteArray(), "GBK");
- //myString = EncodingUtils.getString(baf.toByteArray(), "GBK");
- //myString = new String(baf.toByteArray());這個出現亂碼,要在txt檔案儲存時選中utf-8
- } catch(Exception e) {
- myString = e.getMessage();
- }
- tv.setText(myString);
- this.setContentView(tv);
- }
- }