顯示廣告
隱藏 ✕
看板 KnucklesNote
作者 Knuckles (站長 那克斯)
標題 [AndroidStudio] 使用 AsyncHttpClient 存取網路資料
時間 2016-02-14 Sun. 06:45:26


AsyncHttpClient 是一個在Android上用來存取網路的第三方函式庫

官網 http://loopj.com/android-async-http/

使用方法

在 build.gradle (Module: app) 的 dependencies { 裡加上
    compile 'com.loopj.android:android-async-http:1.4.9'

使用到 Header 時需要
import cz.msebera.android.httpclient.Header;

要讀取 JSON 網頁時使用
String url = "http://disp.cc/api/board.php";
AsyncHttpClient client = new AsyncHttpClient();
RequestParams params = new RequestParams();
params.put("act", "blist");
params.put("limitNum", "5");
client.get(url, params, new JsonHttpResponseHandler() {   
	
   

    @Override
    public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
        // Root JSON in response is an dictionary i.e { "data : [...] }
        // Handle resulting parsed JSON response here
        if (response.optInt("isSuccess") != 1) {
            Toast.makeText(mContext, "Error:" + response.optString("errorMessage"), Toast.LENGTH_LONG).show();
            return;
        }
        JSONObject data = response.optJSONObject("data");
        int totalNum = data.optInt("totalNum");
        Log.d("test","totalNum: " + totalNum);
    }

    @Override
    public void onFailure(int statusCode, Header[] headers, String res, Throwable t) {
        // called when response HTTP status is "4XX" (eg. 401, 403, 404)
        Toast.makeText(getApplicationContext(), "Error: " + statusCode + " " + e.getMessage(), Toast.LENGTH_LONG).show();
    }
});
使用 GET 的方法傳送 act=blist 與 limitNum=5 兩項資料,
也可以在網址 url 後加上 "?act=blist&limitNum=5" 就好
取得的 JSON 資料會像這樣: http://disp.cc/api/board.php?act=blist&limitNum=5

要使用 POST 的方法傳送資料的話,就把 client.get 改成 client.post
這樣 params 就會是用 POST 的方法來傳送


保存網頁Cookie

例如要做登入功能的話,使用
AsyncHttpClient client = new AsyncHttpClient();
PersistentCookieStore cookieStore = new PersistentCookieStore(this);
client.setCookieStore(cookieStore);
就會自動將網頁Cookie存到SharedPreferences
關閉APP再打開也會保留著

但是這個儲存的 Cookie 和 WebView 使用的 Cookie 不相同
要把 PersistentCookieStore 儲存的值取出來
利用 CookieManager 轉存成 WebView 使用的 Cookie
        PersistentCookieStore cookieStore = new PersistentCookieStore(this);
        List<Cookie> cookies = cookieStore.getCookies();
        CookieManager cookieManager = CookieManager.getInstance();
        if (Build.VERSION.SDK_INT < 21) {
            CookieSyncManager.createInstance(this); //API 21 前要執行這個才不會當掉
        }
        for (Cookie eachCookie : cookies) {
            String cookieString = eachCookie.getName() + "=" + eachCookie.getValue();
            cookieManager.setCookie("http://disp.cc", cookieString);
        }


存取網路資料時加上「載入中...」的提示訊息
[圖]


加上兩個成員函式
    private void showLoadingDialog(String message){
        if(message==null){
            message = "載入中...";
        }
        if(mLoadingDialog==null){
            mLoadingDialog = new ProgressDialog(this);
            mLoadingDialog.setMessage(message);
        }
        mLoadingDialog.show();
    }

    private void dismissLoadingDialog(){
        if(mLoadingDialog!=null) {
            mLoadingDialog.dismiss();
        }
    }

加上類別的 onDestroy 事件,當程式結束前關掉載入中的訊息方塊
    @Override
    protected void onDestroy() {
        dismissLoadingDialog();
        super.onDestroy();
    }


加進 AsyncHttpClent 的程式裡
String url = "http://disp.cc/api/board.php";
AsyncHttpClient client = new AsyncHttpClient();
RequestParams params = new RequestParams();
params.put("act", "blist");
params.put("limitNum", "5");
showLoadingDialog("載入中..."); //顯示載入中的訊息方塊
client.get(url, params, new JsonHttpResponseHandler() {   
	
   

    @Override
    public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
       dismissLoadingDialog(); //關閉載入中的訊息方塊
       // Root JSON in response is an dictionary i.e { "data : [...] }
       // Handle resulting parsed JSON response here
    }

    @Override
    public void onFailure(int statusCode, Header[] headers, String res, Throwable t) {
        dismissLoadingDialog(); //關閉載入中的訊息方塊
        // called when response HTTP status is "4XX" (eg. 401, 403, 404)
    }
});



--
※ 作者: Knuckles 時間: 2016-02-14 06:45:26
※ 編輯: Knuckles 時間: 2017-01-09 19:59:02
※ 看板: KnucklesNote 文章推薦值: 0 目前人氣: 0 累積人氣: 1437 
分享網址: 複製 已複製
r)回覆 e)編輯 d)刪除 M)收藏 ^x)轉錄 同主題: =)首篇 [)上篇 ])下篇