閱讀753 返回首頁    go 阿裏雲 go 技術社區[雲棲]


Android開發16——獲取網絡資源之基礎應用

一、項目背景
在Android開發中有一項非常廣泛的應用:Android項目獲取另一個web項目的資源或者返回的數據。本博文介紹了獲取另一個web項目的資源。有一個web項目,在其WebRoot文件夾下有一個靜態頁麵test.html。現有一個Android項目要獲取到該頁麵的html代碼顯示在TextView中。

 


二、實例代碼

public class MainActivity extends Activity
{
 private EditText txtPath;
 private Button btnShowHtml;
 private TextView txtViewHtml;
 
 @Override
 public void onCreate(Bundle savedInstanceState)
 {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
  txtPath = (EditText)this.findViewById(R.id.txtPath);
  btnShowHtml = (Button)this.findViewById(R.id.btnShowHtml);
  txtViewHtml = (TextView)this.findViewById(R.id.txtViewHtml);
  btnShowHtml.setOnClickListener(new ShowHtmlListener());
 }
 
 private final class ShowHtmlListener implements View.OnClickListener
 {
  @Override
  public void onClick(View v)
  {
   String path = txtPath.getText().toString();
   try
   {
    String html = HtmlService.getHtml(path);
    txtViewHtml.setText(html);
   }
   catch (Exception e)
   {
    Toast.makeText(MainActivity.this, "獲取網頁元素失敗", Toast.LENGTH_SHORT).show();
   }
  } 
 }
}


package cn.xy.html.service;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import cn.xy.html.util.IOUtils;
/**
 * Html獲取業務類
 * @author 徐越
 */
public class HtmlService
{
 /**
  * 獲取網頁html源代碼
  * @param path
  * @return
  */
 public static String getHtml(String path) throws Exception
 {
  String html = "";
  // 把路徑包裝成URL對象
  URL url = new URL(path);
  // 基於http協議的連接對象
  HttpURLConnection conn = (HttpURLConnection) url.openConnection();
  // 超時時間5s
  conn.setReadTimeout(5000);
  // 獲取傳輸方式
  conn.setRequestMethod("GET");
  // 若響應碼為200說明請求成功
  if(200 == conn.getResponseCode())
  {
   InputStream instream = conn.getInputStream();
   byte[] data = IOUtils.read(instream);
   // 真實情況是讀出請求頭的charset值
   html = new String(data,"UTF-8"); 
  }
  return html;
 }
}


package cn.xy.html.util;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
/**
 * IO操作工具類
 * @author xy
 */
public class IOUtils
{
 /**
  * 獲取輸入流的方法
  */
 public static byte[] read(InputStream instream) throws IOException
 {
  ByteArrayOutputStream bos = new ByteArrayOutputStream();
  byte[] buffer = new byte[1024];
  int len = 0;
  while ((len = instream.read(buffer)) != -1)
  {
   bos.write(buffer, 0, len);
  }
  return bos.toByteArray();
 }
}

    <TextView  
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:text="網絡頁麵路徑"
    />
    <!-- 網址輸入不能使localhost或127.0.0.1 -->
    <!-- 因為android是一個操作係統,輸入localhost或127.0.0.1會到本操作係統下去找某web應用,所以要使用局域網的ip -->
    <EditText  
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:
     android:text="https://***.***.***.***:8080/ad_20_web/test.html"
    />
    <Button  
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content"
     android:text="獲取html"
     android:
    />
    <ScrollView android:layout_width="wrap_content" android:layout_height="wrap_content">
     <TextView  
      android:layout_width="fill_parent" 
      android:layout_height="wrap_content"
      android: />
    </ScrollView>

ScrollView標簽為TextView增加滾動條。

當然不能忘記訪問網絡需要權限

<!-- 訪問網絡權限 -->
<uses-permission android:name="android.permission.INTERNET" />


三、總結
HtmlService中的方法其實可以獲取任意類型的數據,因為其中一個環節是獲取了byte[],拿到這個字節數組後我們可以根據不同類型的數據進行不同的操作。比如拿到一個圖片byte[],就需要使用Bitmap工廠將其轉化為Bitmap然後賦給ImageView控件。所以我們要熟悉獲取網絡資源的一般步驟。

 

 

最後更新:2017-04-03 05:40:39

  上一篇:go Android開發7——android.database.CursorIndexOutOfBoundsException:Index -1 requested, with a size of 1
  下一篇:go Android開發3——查看和輸出日誌信息