編輯:關於 Android 開發
手機這東西,天生就是要上網的。所以網絡通信幾乎是每個 App 的必修課。本文從最直觀的 WebView 開始,再依次動手實作 HttpURLConnection、HttpClient 以及第三方框架 Android-Async-Http,把最常見的幾條路徑都走一遍。
布局很簡單:一個輸入框填網址,一個按鈕觸發加載,下面一塊 WebView 負責渲染網頁。
<!--{cke_protected}{C}%3C!%2D%2D%3Fxml%20version%3D%221.0%22%20encoding%3D%22utf-8%22%3F%2D%2D%3E--> <linearlayout xmlns:android="https://schemas.android.com/apk/res/android" xmlns:tools="https://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:layout_margin="10dp" android:padding="10dp" tools:context="com.example.jared.webviewstudy.MainActivity"> <linearlayout android:layout_width="match_parent" android:layout_height="wrap_content"> <edittext android:id="@+id/netAddress" android:layout_weight="1" android:layout_width="wrap_content" android:layout_height="wrap_content"><button android:id="@+id/openNetAddress" android:layout_height="wrap_content" android:layout_width="wrap_content" android:layout_weight="0" android:text="Open" android:textallcaps="false"> <webview android:id="@+id/webView" android:layout_width="match_parent" android:layout_height="match_parent"> </webview></button></edittext></linearlayout></linearlayout>
Activity 裡的三步:開啟 JavaScript 支持、掛一個 WebViewClient 讓頁面留在自己的 WebView 內加載、最後把輸入的域名拼上 https:// 交給 loadUrl。
package com.example.jared.webviewstudy; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.Button; import android.widget.EditText; public class MainActivity extends AppCompatActivity { private WebView myWebView; private EditText networkAddr; private Button openNetwork; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); networkAddr = (EditText)findViewById(R.id.netAddress); myWebView = (WebView)findViewById(R.id.webView); openNetwork = (Button)findViewById(R.id.openNetAddress); openNetwork.setOnClickListener(new myOnClickListener()); } class myOnClickListener implements View.OnClickListener { @Override public void onClick(View view) { myWebView.getSettings().setJavaScriptEnabled(true); myWebView.setWebViewClient(new WebViewClient() { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { view.loadUrl(url); return true; } }); String networkAddress = networkAddr.getText().toString(); myWebView.loadUrl("https://"+networkAddress); } } }
千萬別忘了在清單文件裡開網絡權限,否則運行時會直接拋異常:
<uses-permission android:name="android.permission.INTERNET"> </uses-permission>
這裡的關鍵是 setWebViewClient:實例化一個 WebViewClient 並在 shouldOverrideUrlLoading 中自行 loadUrl,頁面才不會被系統瀏覽器搶走。運行後分別打開百度和自己的部落格看看:

界面確實樸素,但作為入門驗證已經足夠了。
真正的網絡編程通常基於 HTTP。Android 提供了兩條老路:Google 官方推薦的 HttpURLConnection,以及歷史更悠久的 HttpClient(從 API 23 起被移除,需要自行引入)。先新建工程,布局上放一個「發送請求」按鈕,下面用 ScrollView 包住 TextView,方便瀏覽較長的返回內容。
<!--{cke_protected}{C}%3C!%2D%2D%3Fxml%20version%3D%221.0%22%20encoding%3D%22utf-8%22%3F%2D%2D%3E--> <linearlayout xmlns:android="https://schemas.android.com/apk/res/android" xmlns:tools="https://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:layout_margin="10dp" tools:context="com.example.jared.httpurlconnectionstudy.MainActivity"><button android:id="@+id/sendRequest" android:text="發送請求" android:layout_width="match_parent" android:layout_height="wrap_content"> <scrollview android:layout_width="match_parent" android:layout_height="match_parent"> <textview android:id="@+id/response" android:layout_width="match_parent" android:layout_height="wrap_content"> </textview></scrollview></button></linearlayout>
MainActivity 裡同時示範了兩種寫法,注意網絡操作都放在子線程,結果通過 Handler 回到主線程更新界面:
package com.example.jared.httpurlconnectionstudy; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.TextView; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; public class MainActivity extends AppCompatActivity { private static final int SHOW_RESPONSE = 1; private Button sendRequestBtn; private TextView responseView; private Handler mHandler = new Handler(){ @Override public void handleMessage(Message msg) { switch (msg.what) { case SHOW_RESPONSE: String responseContent = (String)msg.obj; responseView.setText(responseContent); break; } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ActionBar actionBar = getSupportActionBar(); actionBar.hide(); setContentView(R.layout.activity_main); responseView = (TextView)findViewById(R.id.response); sendRequestBtn = (Button)findViewById(R.id.sendRequest); sendRequestBtn.setOnClickListener(new myOnClickListener()); } private class myOnClickListener implements View.OnClickListener { @Override public void onClick(View view) { switch (view.getId()) { case R.id.sendRequest: String url = "https://www.baidu.com"; //sendRequestWithHttpURLConnection(url); sendRequestWithHttpClient(url); break; default: break; } } } private void sendRequestWithHttpClient(final String url) { new Thread(new Runnable() { @Override public void run() { try { HttpClient httpClient = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(url); HttpResponse httpResponse = httpClient.execute(httpGet); if(httpResponse.getStatusLine().getStatusCode() == 200) { HttpEntity entity = httpResponse.getEntity(); String response = EntityUtils.toString(entity, "utf-8"); Message message = new Message(); message.what = SHOW_RESPONSE; message.obj = response.toString(); mHandler.sendMessage(message); } } catch (Exception e) { e.printStackTrace(); } } }).start(); } private void sendRequestWithHttpURLConnection(final String url) { new Thread(new Runnable() { @Override public void run() { HttpURLConnection connection = null; try { URL mUrl = new URL(url); connection = (HttpURLConnection)mUrl.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(8000); connection.setReadTimeout(8000); InputStream in = connection.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); StringBuilder response = new StringBuilder(); String line; while((line = reader.readLine()) != null) { response.append(line); } Message message = new Message(); message.what = SHOW_RESPONSE; message.obj = response.toString(); mHandler.sendMessage(message); } catch (Exception e) { e.printStackTrace(); } finally { if (connection != null) { connection.disconnect(); } } } }).start(); } }
要用 HttpClient,需要從 SDK 的 platforms/android-23/optional 目錄下把 jar 包拷到工程的 libs 裡,並在 build.gradle 中聲明:
// Apache Http android { useLibrary 'org.apache.http.legacy' } // Header dependencies { compile "org.apache.httpcomponents:httpcore:4.3.2" }
這樣配置完,HttpClient 就能正常工作了;引入其他第三方庫的思路也基本一致。

常用的網絡框架裡,android-async-http 是相當經典的一個。需要下載兩個 jar:框架本體(loopj.com/android-async-http/)以及它依賴的 httpclient(4.4.1.1 版本),都放進 libs 目錄,然後修改 build.gradle:
dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) testCompile 'junit:junit:4.12' compile 'com.android.support:appcompat-v7:23.1.1' compile files('libs/android-async-http-1.4.9.jar') compile files('libs/httpclient-4.4.1.1.jar') }
切換到 project 視角確認文件位置:

只需新增一個方法,框架內部已經幫你處理好線程切換,不再需要自己 new Thread、也不再需要 Handler:
private void sendRequestWithAsyncHttpClient(String url) { AsyncHttpClient client = new AsyncHttpClient(); client.get(url, new AsyncHttpResponseHandler() { @Override public void onSuccess(int i, Header[] headers, byte[] bytes) { try { String response = new String(bytes, 0, bytes.length, "UTF-8"); responseView.setText(response); }catch (Exception e) { e.printStackTrace(); } } @Override public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) { } }); }
運行效果與前面一致,但程式碼量少了大半——這就是框架的價值。順帶一提,這個庫早已停止維護,新專案更建議直接上 OkHttp 或 Retrofit。
網絡編程的兩大塊(WebView 與 HTTP 請求)就先梳理到這裡。也要感謝朋友的提醒:基礎知識只是起點,真實項目裡會用到大量框架,後面還得慢慢補。
Android MediaPlayer 音樂播放實作指南
Android MediaPlayer 音樂播放實作指南 MediaPlayer 是 Android 中用於播放音訊與影片的常用元件。若要做一個簡單的音樂播放器,通常會搭
項目源碼分享:高仿天天動聽 5 的 Android 音樂播放器
項目源碼分享:高仿天天動聽 5 的 Android 音樂播放器 這是一個完整度相當高的 Android 音樂播放器項目,界面與交互大量參考了天天動聽 5。除了本地播放器的
Android 實用小專案:打造一個可異步載入資料的在線音樂播放器
Android 實用小專案:打造一個可異步載入資料的在線音樂播放器 從大一開始自學 Java 與 Android,到現在差不多滿一年,終於走到專案實戰這一步。第一個作品
Android 仿當樂游戲詳情頁(二):層次布局、滑動狀態與截圖旋轉
Android 仿當樂游戲詳情頁(二):層次布局、滑動狀態與截圖旋轉 本文接續前一篇分析,重點在於實作當樂風格游戲詳情頁的基本視覺與互動效果。整個頁面可拆解為三個主要層次