Android之Http通訊——4.Android HTTP請求方式:HttpClient

來源:互聯網
上載者:User

標籤:android   http   httpclient   post   get   

本節引言:

上節講了HttpURLConnection,本節就到HttpClient了,Apache給我們提供的HttpClient(簡單的Http用戶端),
不過畢竟不是親兒子,HttpClient在API 21版本後就給Google棄用了,而我們實際開發中,很多頁面都不是通過
一個簡單的URL就可以訪問的,可能需要登陸或者相關許可權才可以訪問,這就涉及到了Session,Cookie等的問題了;
當然我們可以用HttpURLConnection來實現,但是有點麻煩,而用HttpClient可以簡單點;HttpClient用於接收/發送
Http請求/響應,但不快取服務器響應,不執行HTML頁面潛入的JS代碼,不會對頁面內容進行任何解析,處理;
要改掉廢話太多的習慣,SO簡化博文,開始本節內容吧:

HttpClient使用流程:

基本流程:

HttpClient使用樣本:1.發送GET請求

嗯,就寫個簡單的發送GET請求的代碼吧:

package com.example.httpclientdemo;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 android.app.Activity;import android.os.Bundle;import android.os.Handler;import android.os.Message;import android.view.View;import android.view.View.OnClickListener;import android.webkit.WebView;import android.widget.Button;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("http://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編碼:
然後和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("http://www.baidu.com"+"?"+param);

接著貼下運行:

2.發送POST請求

POST請求比GET稍微複雜一點,建立完HttpPost對象後,通過NameValuePair集合來儲存等待提交
的參數,並將參數傳遞到UrlEncodedFormEntity中,最後調用setEntity(entity)完成,
HttpClient.execute(HttpPost)即可;這裡就不寫例子了,暫時沒找到Post的網站,又不想
自己寫個Servlet,So,直接貼核心代碼吧~

核心代碼:

    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();    }
3.胡說八道

其實關於HttpClient的例子有很多,比如筆者曾經用它來抓學校教務系統上學生的課程表:
這就涉及到Cookie,類比登陸的東西,說到抓資料(爬蟲),一般我們是搭配著JSoup來解析
抓到資料的,有興趣可以自己查閱相關資料,至於筆者的畢設,代碼很爛的說,後續有時間
整理在發布出來吧,這裡貼下類比登陸教務系統部分的代碼,大家可以體會下HttpClient:

//獲得連結,類比登入的實現:    public int getConnect(String user, String key) throws Exception {        // 先發送get請求 擷取cookie值和__ViewState值        HttpGet getLogin = new HttpGet(true_url);        // 第一步:主要的HTML:        String loginhtml = "";        HttpResponse loginResponse = new DefaultHttpClient().execute(getLogin);        if (loginResponse.getStatusLine().getStatusCode() == 200) {            HttpEntity entity = loginResponse.getEntity();            loginhtml = EntityUtils.toString(entity);            // 擷取響應的cookie值            cookie = loginResponse.getFirstHeader("Set-Cookie").getValue();            System.out.println("cookie= " + cookie);        }        // 第二步:類比登入        // 發送Post請求,禁止重新導向        HttpPost httpPost = new HttpPost(true_url);        httpPost.getParams().setParameter(ClientPNames.HANDLE_REDIRECTS, false);        // 設定Post提交的頭資訊的參數        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)));// __VIEWSTATE參數,如果變化可以動態抓取擷取        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;        System.out.println("Status= " + Status);        // 重新導向狀態代碼為302        if (Status == 302 || Status == 301) {            // 擷取頭部資訊中Location的值            location = response.getFirstHeader("Location").getValue();            System.out.println(location);            // 第三步:擷取管理資訊的首頁面            // Get請求            HttpGet httpGet = new HttpGet(ip_url + location);// 帶上location地址訪問            httpGet.setHeader("Referer", true_url);            httpGet.setHeader("Cookie", cookie);            // 首頁的html            mainhtml = "";            HttpResponse httpResponseget = new DefaultHttpClient()                    .execute(httpGet);            if (httpResponseget.getStatusLine().getStatusCode() == 200) {                HttpEntity entity = httpResponseget.getEntity();                mainhtml = EntityUtils.toString(entity);            }        }        return Status;    }
總結:

好的,本節關於HttpClient就到這裡吧,內容還是比較簡單的~
下節我們將使用retrofit來封裝我們的HTTP請求,敬請期待~

Android之Http通訊——4.Android HTTP請求方式:HttpClient

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.