編輯:關於 Android 程式設計
上一節談了 HttpURLConnection,這節換 Apache 提供的 HttpClient。它不是「親兒子」——API 21 之後就被 Google 標記為 deprecated 了。但實際開發中,很多頁面並不是一個簡單 URL 就能取到,需要登入或特定權限,這就牽涉到 Session、Cookie。用 HttpURLConnection 當然做得到,只是繁瑣;HttpClient 寫起來會從容一些。
先釐清 HttpClient 的定位:它負責接收/發送 HTTP 請求與响应,不快取伺服器响应,不執行頁面裡的 JS,也不解析頁面內容。它就是個純 transmission 層的工具。

public class MainActivity extends Activity implements OnClickListener {
private Button btnGet;
private WebView wView;
public static final int SHOW_DATA = 0X123;
private String detail = "";
private Handler handler = new Handler() {
public void handleMessage(Message msg) {
if (msg.what == SHOW_DATA) {
wView.loadDataWithBaseURL("", detail, "text/html", "UTF-8", "");
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
setView();
}
private void initView() {
btnGet = (Button) findViewById(R.id.btnGet);
wView = (WebView) findViewById(R.id.wView);
}
private void setView() {
btnGet.setOnClickListener(this);
wView.getSettings().setDomStorageEnabled(true);
}
@Override
public void onClick(View v) {
if (v.getId() == R.id.btnGet) GetByHttpClient();
}
private void GetByHttpClient() {
new Thread() {
public void run() {
try {
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(
"https://www.w3cschool.cc/python/python-tutorial.html");
HttpResponse httpResponse = httpClient.execute(httpGet);
if (httpResponse.getStatusLine().getStatusCode() == 200) {
HttpEntity entity = httpResponse.getEntity();
detail = EntityUtils.toString(entity, "utf-8");
handler.sendEmptyMessage(SHOW_DATA);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
}
}
如果是帶參數的 GET,把參數塞進 List,做完 URL 編碼再跟網址拼接:
List<BasicNameValuePair> params = new LinkedList<BasicNameValuePair>();
params.add(new BasicNameValuePair("user", "豬小弟"));
params.add(new BasicNameValuePair("pawd", "123"));
String param = URLEncodedUtils.format(params, "UTF-8");
HttpGet httpGet = new HttpGet("https://www.baidu.com" + "?" + param);
執行結果:

POST 比 GET 多一步:建立 HttpPost 之後,用 NameValuePair 清單收集參數,包成 UrlEncodedFormEntity,再 setEntity() 掛上去,最後一樣交給 execute()。
private void PostByHttpClient(final String url) {
new Thread() {
public void run() {
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("user", "豬大哥"));
params.add(new BasicNameValuePair("pawd", "123"));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
httpPost.setEntity(entity);
HttpResponse httpResponse = httpClient.execute(httpPost);
if (httpResponse.getStatusLine().getStatusCode() == 200) {
HttpEntity entity2 = httpResponse.getEntity();
detail = EntityUtils.toString(entity2, "utf-8");
handler.sendEmptyMessage(SHOW_DATA);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
}
筆者當年用它去抓學校教務系統的課表,這就繞到 Cookie 與模擬登入。爬蟲這條路通常是 HttpClient 抓資料、JSoup 解析,有興趣可以自己深入研究。下面貼一段登入部分的程式碼,讓大家體會 Cookie 是怎麼在多次請求之間傳遞的:
public int getConnect(String user, String key) throws Exception {
// 第一步:先發 GET 拿 cookie 與 __ViewState
HttpGet getLogin = new HttpGet(true_url);
String loginhtml = "";
HttpResponse loginResponse = new DefaultHttpClient().execute(getLogin);
if (loginResponse.getStatusLine().getStatusCode() == 200) {
HttpEntity entity = loginResponse.getEntity();
loginhtml = EntityUtils.toString(entity);
cookie = loginResponse.getFirstHeader("Set-Cookie").getValue();
System.out.println("cookie= " + cookie);
}
// 第二步:帶著 cookie 發 POST 模擬登入,並禁止自動重導
HttpPost httpPost = new HttpPost(true_url);
httpPost.getParams().setParameter(ClientPNames.HANDLE_REDIRECTS, false);
httpPost.setHeader("User-Agent",
"Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; rv:11.0) like Gecko");
httpPost.setHeader("Referer", true_url);
httpPost.setHeader("Cookie", cookie);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("__VIEWSTATE", getViewState(loginhtml)));
params.add(new BasicNameValuePair("Button1", ""));
params.add(new BasicNameValuePair("hidPdrs", ""));
params.add(new BasicNameValuePair("hidsc", ""));
params.add(new BasicNameValuePair("lbLanguage", ""));
params.add(new BasicNameValuePair("RadioButtonList1", "%D1%A7%C9%FA"));
params.add(new BasicNameValuePair("txtUserName", user));
params.add(new BasicNameValuePair("TextBox2", key));
params.add(new BasicNameValuePair("txtSecretCode", ""));
httpPost.setEntity(new UrlEncodedFormEntity(params, "gb2312"));
HttpResponse response = new DefaultHttpClient().execute(httpPost);
int Status = response.getStatusLine().getStatusCode();
if (Status == 200) return Status;
// 第三步:遇到 301/302 就手動取出 Location 再跳一次
if (Status == 302 || Status == 301) {
location = response.getFirstHeader("Location").getValue();
HttpGet httpGet = new HttpGet(ip_url + location);
httpGet.setHeader("Referer", true_url);
httpGet.setHeader("Cookie", cookie);
String mainhtml = "";
HttpResponse getResponse = new DefaultHttpClient().execute(httpGet);
if (getResponse.getStatusLine().getStatusCode() == 200) {
mainhtml = EntityUtils.toString(getResponse.getEntity());
}
}
return Status;
}
幾個值得記下的細節:登入前一定要先 GET 一次拿 Cookie;__VIEWSTATE 這類隱藏欄位最好動態抓取而非寫死;關掉自動重導(HANDLE_REDIRECTS = false)才能自己掌握 302 的落點。
HttpClient 就到這裡,難度其實不高。下一節我們會用 Retrofit 來封裝 HTTP 請求,敬請期待。
用 NineOldAndroids 實作絢麗的 ListView 左右滑動刪除效果
今天繼續帶來自訂控制項的實作——為 ListView 加上左右滑動刪除 Item 的效果。之前曾用 Scroller 類別實作過類似功能,但借鏡通知欄的滑動刪除後,我發現
Android 自訂軟鍵盤:Keyboard 與 KeyboardView 完整實作教學
翻資料時無意間發現了 android.inputmethodservice.Keyboard 這個類,原來 Android 早就內建了自訂鍵盤的能力,不需要自己拿一堆 B
Android 頂部吸附視圖(Sticky Header)實作詳解
不知從什麼時候開始,這種效果在 UI 設計中流行了起來。先來看看效果: 在支付寶、美團等許多 App 中都能看到它的身影。要實現這個效果,我們可以分析一下思路: 我們需
實例講解 Android 自定義組合控件的方法
自定義 View 大致可分為四類:繼承 View、組合 View、自繪 View(用 Paint 和 Canvas)、自定義 ViewGroup(Widget)。本文聚焦