以HttpURLConnection連接網頁資料


設定INTERNET權限


只要在app中會使用到網際網路存取資料, 則必須設定INTERNET權限. 如下片段第一列

<uses-permission android:name="android.permission.INTERNET" />
<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>								
								



開始連線存取


  • 1. 建立URL物件實體, 將連結網址url以字串方式傳遞參數
  • 2. 使URL物件實體呼叫openConnection()方法傳回轉型為HttpURLConnection物件實體
  • 3. 將參數資料進行URL編碼
  • 4. 取得輸出串流傳遞參數資料
  • 5. 再以HttpURLConnection物件實體呼叫connect()進行連線
  • 6. 最後透過呼叫getInputStream()傳回輸入串流, 進行資料讀取


先來看到處理參數資料的方法: queryString()

private String queryString(ContentValues params){
    Set keys = params.keySet();
    StringBuffer sb = new StringBuffer();
    try {
        for (String key : keys) {
            sb.append(URLEncoder.encode(key, "UTF-8"));
            sb.append("=");
            sb.append(URLEncoder.encode(params.getAsString(key), "UTF-8"));
            sb.append("&");
        }
        sb.deleteCharAt(sb.length()-1);
        return sb.toString();
    }catch (Exception e){
        return null;
    }
}

								



將URL編碼的參數傳遞到輸出串流



            URL url = new URL("https://www.bradchao.com/v2/apptest/postTest1.php");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");

            ContentValues params = new ContentValues();
            params.put("account", "brad");
            params.put("passwd", "1234");

            BufferedWriter writer = new BufferedWriter(
                    new OutputStreamWriter(conn.getOutputStream()));
            writer.write(queryString(params));
            writer.flush();
            writer.close();

								


則處理範例如下:

    private void postConnect(){
        try{
            URL url = new URL("https://www.bradchao.com/v2/apptest/postTest1.php");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");

            ContentValues params = new ContentValues();
            params.put("account", "brad");
            params.put("passwd", "1234");

            BufferedWriter writer = new BufferedWriter(
                    new OutputStreamWriter(conn.getOutputStream()));
            writer.write(queryString(params));
            writer.flush();
            writer.close();

            conn.connect();

            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String data = reader.readLine();
            reader.close();

            Log.v("brad", data);

        }catch (Exception e){
            Log.v("brad", e.toString());
        }

    }

								

原始碼分享: Github

影片教學