Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android HttpURLConnection 網路請求實作

編輯:關於 Android 程式設計

HttpURLConnection 是 Android 上進行 HTTP 連線的基礎工具。本文示範如何以 GET 方式抓取網頁 HTML 內容,並顯示於畫面上,重點在於串流讀取與編碼處理。

一、版面配置

使用 ScrollView 包裹 TextView,方便顯示較長的內容:

<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" xmlns:tools="https://schemas.android.com/tools" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <ScrollView android:layout_width="fill_parent" android:layout_height="fill_parent" > <TextView android:id="@+id/textView" android:layout_width="fill_parent" android:layout_height="wrap_content" /> </ScrollView> </LinearLayout>

二、串流讀取工具

StreamTool 負責把 InputStream 轉為位元組陣列,使用 1KB 緩衝區迴圈讀取,是後續所有網路讀取的基礎:

package com.example.utils; import java.io.ByteArrayOutputStream; import java.io.InputStream; public class StreamTool { public static byte[] readInputStream(InputStream inStream) throws Exception { ByteArrayOutputStream outStream = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len = 0; while ((len = inStream.read(buffer)) != -1) { outStream.write(buffer, 0, len); } inStream.close(); return outStream.toByteArray(); } } 

三、抓取網頁的 Service

HtmlService 建立 HttpURLConnection 連線,設定請求方法與逾時時間,再將取得的位元組以 UTF-8 解碼為字串:

package com.example.image; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import com.example.utils.StreamTool; public class HtmlService { public static String getHtml(String path) throws Throwable { URL url = new URL(path); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setConnectTimeout(5 * 1000); InputStream inStream = conn.getInputStream(); byte[] data = StreamTool.readInputStream(inStream); String html = new String(data, "utf-8"); return (html); } } 

四、在 Activity 中呼叫

MainActivity 取得 TextView 後呼叫 HtmlService,並以 try-catch 處理例外:

package com.example.image; import android.app.Activity; import android.os.Bundle; import android.util.Log; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends Activity { private static final String TAG = "htmlcodeview"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_image); TextView textView = (TextView) this.findViewById(R.id.textView); try { textView.setText(HtmlService.getHtml("https://www.baidu.com")); } catch (Throwable e) { Log.e(TAG, e.toString()); Toast.makeText(MainActivity.this, "error", 1).show(); } } } 

別忘了在 AndroidManifest.xml 加入網路權限:

<uses-permission android:name="android.permission.INTERNET"/>

提醒:在較新版本的 Android 中,網路操作需放在子執行緒,並在主要執行緒更新 UI,上述範例著重於 HttpURLConnection 的核心用法。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved