編輯:關於 Android 開發
在引入任何第三方框架之前,先直接用 SDK 內建的 HttpURLConnection 走一次 GET,有助於理解後續 Volley、Retrofit 到底替你做了什麼。
整段流程可以拆成五步:開連線 → 設定逾時與標頭 → 檢查回應碼 → 讀取串流並組字串 → 透過 Handler 把結果送回主線程更新 UI。
package com.jredu.helloworld.activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.TextView;
import com.jredu.helloworld.R;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class HttpUrlConnectionGetActivity extends AppCompatActivity {
WebView webView;
Button button;
TextView success;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_http_url_connection_get);
webView = (WebView) findViewById(R.id.baidu);
success = (TextView) findViewById(R.id.success);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// 網路操作必須放在子執行緒,否則會觸發
// NetworkOnMainThreadException
new Thread(new Runnable() {
@Override
public void run() {
HttpUrlConnectionGet();
}
}).start();
}
});
}
public void HttpUrlConnectionGet() {
HttpURLConnection urlConnection = null;
InputStream is = null;
StringBuilder sb = new StringBuilder();
try {
URL url = new URL("https://apis.baidu.com/txapi/tiyu/tiyu?num=10&page=1");
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setConnectTimeout(5 * 1000); // 連線逾時
urlConnection.setReadTimeout(5 * 1000); // 讀取逾時
urlConnection.setRequestProperty("apikey",
"fc642e216cd19906f642ee930ce28174"); // 自訂請求標頭
urlConnection.connect();
if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
is = urlConnection.getInputStream();
byte[] bytes = new byte[1024];
int i = 0;
while ((i = is.read(bytes)) != -1) {
sb.append(new String(bytes, 0, i, "utf-8"));
}
is.close();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
// 把結果交給主線程
Message message = handler.obtainMessage(1, sb.toString());
handler.sendMessage(message);
}
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if (msg != null && msg.what == 1) {
String s = (String) msg.obj;
webView.getSettings().setDefaultTextEncodingName("utf-8");
webView.getSettings().setJavaScriptEnabled(true);
webView.loadDataWithBaseURL(null, s, "text/html", "utf-8", null);
}
}
};
}
一定要放在子執行緒。從 Android 4.0 起,主線程禁止執行網路 I/O,否則直接拋 NetworkOnMainThreadException。
逾時要主動設定。預設值可能長到讓使用者以為 App 當機,連線與讀取逾時建議都設在數秒內。
串流要在 finally 中收尾。InputStream 與 HttpURLConnection 都應該確實關閉,否則在頻繁請求時容易耗盡連線。實務上更推薦用 try-with-resources 自動關閉。
別忘了網路權限。AndroidManifest.xml 中需要 <uses-permission android:name="android.permission.INTERNET" />。
為什麼用 Handler 而不是 runOnUiThread?兩者都能回到主線程,但 Handler 的訊息模型更適合有多種請求類型、需要依 what 分派的情境,也更容易在 Activity 銷毀時統一 removeMessages() 清理。
註冊介面設計與實作(二):註冊業務邏輯的實作
註冊介面設計與實作(二):註冊業務邏輯的實作 承接上一篇的註冊介面設計,本篇聚焦於註冊業務邏輯的實作。核心在於一個 checkform 方法,用來驗證表單:帳號不可為空、
Android 屬性動畫實作:用 Java 程式碼驅動動畫
用 Java 程式碼實現屬性動畫 除了透過 XML 檔定義動畫之外,屬性動畫也可以用 Java 程式碼來靈活控制。下面用一個簡單的位移範例帶大家走一遍。 先看佈局檔:
Android 內部存儲讀寫文件:做一個會記住帳號密碼的登錄頁
Android 內部存儲讀寫文件:做一個會記住帳號密碼的登錄頁 先理清幾個存儲概念 RAM:運行內存,相當於電腦的內存條,掉電即失。 ROM:內部存儲空間,相當於電腦
自定義 PinnedHeaderListView:實現仿聯繫人分組懸浮列表
自定義 PinnedHeaderListView:實現仿聯繫人分組懸浮列表 像聯繫人那樣的分組懸浮列表,是很多應用常見的需求。本文透過自定義 PinnedHeaderLi