一区二区三区日韩精品-日韩经典一区二区三区-五月激情综合丁香婷婷-欧美精品中文字幕专区

分享

7.1.4 Android HTTP請(qǐng)求方式:HttpClient 

 小飛苑 2017-01-04

本節(jié)引言:

在上一節(jié)中我們對(duì)HttpURLConnection進(jìn)行了學(xué)習(xí),本節(jié)到第二種方式:HttpClient,盡管被Google 棄用了,但是我們我們平時(shí)也可以拿HttpClient來抓下包,配合Jsoup解析網(wǎng)頁效果更佳!HttpClient 用于接收/發(fā)送Http請(qǐng)求/響應(yīng),但不緩存服務(wù)器響應(yīng),不執(zhí)行HTML頁面潛入的JS代碼,不會(huì)對(duì)頁面內(nèi)容 進(jìn)行任何解析,處理!開始本節(jié)內(nèi)容!


1.HttpClient使用流程

基本流程


2.HttpClient使用示例

1)使用HttpClient發(fā)送GET請(qǐng)求

直接貼下簡(jiǎn)單的發(fā)送Get請(qǐng)求的代碼:

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./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();
    }

}

運(yùn)行截圖

另外,如果是帶有參數(shù)的GET請(qǐng)求的話,我們可以將參數(shù)放到一個(gè)List集合中,再對(duì)參數(shù)進(jìn)行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)使用HttpClient發(fā)送POST請(qǐng)求

POST請(qǐng)求比GET稍微復(fù)雜一點(diǎn),創(chuàng)建完HttpPost對(duì)象后,通過NameValuePair集合來存儲(chǔ)等待提交 的參數(shù),并將參數(shù)傳遞到UrlEncodedFormEntity中,最后調(diào)用setEntity(entity)完成, HttpClient.execute(HttpPost)即可;這里就不寫例子了,暫時(shí)沒找到Post的網(wǎng)站,又不想 自己寫個(gè)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抓數(shù)據(jù)示例(教務(wù)系統(tǒng)數(shù)據(jù)抓取)

其實(shí)關(guān)于HttpClient的例子有很多,比如筆者曾經(jīng)用它來抓學(xué)校教務(wù)系統(tǒng)上學(xué)生的課程表: 這就涉及到Cookie,模擬登陸的東西,說到抓數(shù)據(jù)(爬蟲),一般我們是搭配著JSoup來解析 抓到數(shù)據(jù)的,有興趣可以自己查閱相關(guān)資料,這里貼下筆者畢設(shè)app里獲取網(wǎng)頁部分的關(guān)鍵 代碼!大家可以體會(huì)下:

HttpClient可以通過下述代碼獲取與設(shè)置Cookie: HttpResponse loginResponse = new DefaultHttpClient().execute(getLogin); 獲得Cookie:cookie = loginResponse.getFirstHeader("Set-Cookie").getValue(); 請(qǐng)求時(shí)帶上Cookie:httpPost.setHeader("Cookie", cookie);

//獲得鏈接,模擬登錄的實(shí)現(xiàn):
public int getConnect(String user, String key) throws Exception {
    // 先發(fā)送get請(qǐng)求 獲取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);
        // 獲取響應(yīng)的cookie值
        cookie = loginResponse.getFirstHeader("Set-Cookie").getValue();
        System.out.println("cookie= " + cookie);
    }

    // 第二步:模擬登錄
    // 發(fā)送Post請(qǐng)求,禁止重定向
    HttpPost httpPost = new HttpPost(true_url);
    httpPost.getParams().setParameter(ClientPNames.HANDLE_REDIRECTS, false);

    // 設(shè)置Post提交的頭信息的參數(shù)
    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);

    // 設(shè)置請(qǐng)求數(shù)據(jù)
    List<NameValuePair> params = new ArrayList<NameValuePair>();

    params.add(new BasicNameValuePair("__VIEWSTATE",
            getViewState(loginhtml)));// __VIEWSTATE參數(shù),如果變化可以動(dòng)態(tài)抓取獲取
    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", "")); // ( ╯□╰ )逗比正方,竟然不需要驗(yàn)證碼

    // 設(shè)置編碼方式,響應(yīng)請(qǐng)求,獲取響應(yīng)狀態(tài)碼:
    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);

    // 重定向狀態(tài)碼為302
    if (Status == 302 || Status == 301) {
        // 獲取頭部信息中Location的值
        location = response.getFirstHeader("Location").getValue();
        System.out.println(location);
        // 第三步:獲取管理信息的主頁面
        // Get請(qǐng)求
        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;
}

4.使用HttpPut發(fā)送Put請(qǐng)求

示例代碼如下

public static int PutActCode(String actCode, String licPlate, Context mContext) {
    int resp = 0;
    String cookie = (String) SPUtils.get(mContext, "session", "");
    HttpPut httpPut = new HttpPut(PUTACKCODE_URL);
    httpPut.setHeader("Cookie", cookie);
    try {

        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("activation_code", actCode));
        params.add(new BasicNameValuePair("license_plate", licPlate));
        httpPut.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
        HttpResponse course_response = new DefaultHttpClient().execute(httpPut);
        if (course_response.getStatusLine().getStatusCode() == 200) {
            HttpEntity entity2 = course_response.getEntity();
            JSONObject jObject = new JSONObject(EntityUtils.toString(entity2));
            resp = Integer.parseInt(jObject.getString("status_code"));
            return resp;
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return resp;
}

本節(jié)小結(jié):

好的,本節(jié)關(guān)于Android HTTP的第二種請(qǐng)求方式:HttpClient就到這里, 下節(jié)開始我們來學(xué)習(xí)XML以及Json的解析,本節(jié)就到這里,謝謝~

    本站是提供個(gè)人知識(shí)管理的網(wǎng)絡(luò)存儲(chǔ)空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點(diǎn)。請(qǐng)注意甄別內(nèi)容中的聯(lián)系方式、誘導(dǎo)購買等信息,謹(jǐn)防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請(qǐng)點(diǎn)擊一鍵舉報(bào)。
    轉(zhuǎn)藏 分享 獻(xiàn)花(0

    0條評(píng)論

    發(fā)表

    請(qǐng)遵守用戶 評(píng)論公約

    類似文章 更多

    在线免费观看一二区视频| 日本黄色高清视频久久| 免费特黄一级一区二区三区| 精品熟女少妇av免费久久野外 | 亚洲一区二区三区四区| 国产av一区二区三区麻豆| 99久久免费看国产精品| 激情三级在线观看视频| 国产亚洲中文日韩欧美综合网| 国产欧美一区二区另类精品| 国自产拍偷拍福利精品图片| 欧美二区视频在线观看| 久久人妻人人澡人人妻| 亚洲日本韩国一区二区三区| 成人精品欧美一级乱黄| 日韩在线视频精品视频| 亚洲精品偷拍一区二区三区| 91福利免费一区二区三区| 日本不卡在线一区二区三区| 欧美日韩国产亚洲三级理论片 | 一级片二级片欧美日韩| 日韩精品一区二区毛片| 91后入中出内射在线| 精品女同一区二区三区| 日本精品中文字幕人妻| 日韩毛片视频免费观看| 国产一级内片内射免费看| 91爽人人爽人人插人人爽| 欧美日韩三区在线观看| 国产丝袜女优一区二区三区| 在线观看视频国产你懂的| 中文字幕人妻一区二区免费| 邻居人妻人公侵犯人妻视频| 激情亚洲一区国产精品久久| 成人午夜爽爽爽免费视频| 美日韩一区二区精品系列| 国产精品午夜福利免费阅读 | 又黄又硬又爽又色的视频| 成人午夜在线视频观看| 国产专区亚洲专区久久| 国产日韩熟女中文字幕|