編輯:關於 Android 程式設計
所有需要跟後端打交道的 App,第一步都是「送出請求、拿到回應」。這個範例用最經典的 Apache HttpClient 走一遍,把結果直接顯示在 WebView 上,方便驗證字串是否正確。
網路權限必須先宣告,否則會拿到 Permission denied:
<uses-permission android:name="android.permission.INTERNET" />
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
package="com.example.httpdemo1"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.httpdemo1.HttpDemo1Activity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="@+id/myWebTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<WebView
android:id="@+id/webview"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:layout_above="@id/requestBtn"
android:layout_below="@id/myWebTitle" />
<Button
android:id="@+id/requestBtn"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:text="Send Request" />
</RelativeLayout>
package com.example.httpdemo1;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
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 android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.widget.Button;
public class HttpDemo1Activity extends Activity {
private Button mSendReqBtn = null;
private WebView mWebView = null;
private HttpResponse mHttpResponse = null;
private HttpEntity mHttpEntity = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_http_demo1);
mSendReqBtn = (Button) findViewById(R.id.requestBtn);
mSendReqBtn.setOnClickListener(mSendClickListener);
mWebView = (WebView) findViewById(R.id.webview);
}
private OnClickListener mSendClickListener = new OnClickListener() {
@Override
public void onClick(View v) {
// 建立請求物件與 HTTP 客戶端
HttpGet httpGet = new HttpGet("https://www.baidu.com/");
HttpClient httpClient = new DefaultHttpClient();
InputStream inputStream = null;
try {
// 送出請求並取得回應
mHttpResponse = httpClient.execute(httpGet);
mHttpEntity = mHttpResponse.getEntity();
inputStream = mHttpEntity.getContent();
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(inputStream));
String result = "";
String line = "";
while (null != (line = bufferedReader.readLine())) {
result += line;
}
System.out.println(result); // 可在 LogCat 查看
// 把 HTML 字串直接載入 WebView 顯示
mWebView.getSettings().setDefaultTextEncodingName("UTF-8");
// 直接 loadData 會顯示找不到網頁,改用下面這個版本才正常
mWebView.loadDataWithBaseURL(null, result, "text/html", "utf-8", null);
// mWebView.loadUrl("https://www.baidu.com/"); // 直接載入 URL 也行
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (inputStream != null) inputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
};
}
執行結果如下:
這份程式碼有幾處在今天不能直接照抄。第一,DefaultHttpClient 所屬的 Apache HTTP Client 已在 Android 5.1 標記為 deprecated,並從 Android 6.0 起被移除,現在請改用 HttpURLConnection 或 OkHttp。第二,網路操作必須放在背景執行緒,範例直接寫在 onClick 裡會觸發 NetworkOnMainThreadException,正式做法是用非同步任務、Thread 加 Handler,或 Kotlin 的協程。
第三,loadDataWithBaseURL() 之所以比 loadData() 好用,是因為前者能正確處理含 #、% 等特殊字元的 HTML,後者會解析失敗而顯示「找不到網頁」。第四,while 迴圈用 result += line 累加字串,每次迴圈都會產生新的字串物件,改用 StringBuilder 會省下可觀的配置。這些細節,正好都是從「能跑」到「跑得好」的距離。
參考資料:Android Reference — package org.apache.http
https://developer.android.com/reference/org/apache/http/package-summary.html
Qt on Android 實踐:通過 JNI 調用系統原生分享菜單
原文《Sharing with Qt on Android》發表於 2014 年 12 月 12 日。當時我寫的遊戲 GiraffPanic(一款用 Qt & Q
Android 自訂 LinearLayout 實作淘寶詳情頁效果
淘寶詳情頁常見一種雙頁滑動效果:第一頁往上滑到底後,繼續上滑會切換到第二頁;第二頁往下滑到頂後,繼續下滑又會回到第一頁。這種效果可以透過自訂 LinearLayout 搭
登入美區Google Play並完成消費的完整流程
早些年Google服務尚未更新時,可以透過修改GoAgent的proxy.ini來登入美國區Play商店。如今Google Play已推出Google Play for
零基礎打造簡易 Android 日曆:Calendar 結合 GridView
最近閒著沒事做了一個小專案,需要用到日曆。需求並不複雜,只要能簡單地翻看日期即可,所以我選擇了 Java 提供的 Calendar 類,搭配 Android 的 Grid