Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android HTTP 請求之 HttpClient:GET、POST 與模擬登入

編輯:關於 Android 程式設計


開場

上一節談了 HttpURLConnection,這節換 Apache 提供的 HttpClient。它不是「親兒子」——API 21 之後就被 Google 標記為 deprecated 了。但實際開發中,很多頁面並不是一個簡單 URL 就能取到,需要登入或特定權限,這就牽涉到 Session、Cookie。用 HttpURLConnection 當然做得到,只是繁瑣;HttpClient 寫起來會從容一些。

先釐清 HttpClient 的定位:它負責接收/發送 HTTP 請求與响应,不快取伺服器响应,不執行頁面裡的 JS,也不解析頁面內容。它就是個純 transmission 層的工具。


基本流程


一、發送 GET 請求

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 請求

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 請求,敬請期待。


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved