Volley的初使用

Volley的使用

  • 首先得到Volley的源碼,但是需要自己換時(shí)間去弄成jar包,或者使用AS的就作為依賴,所以我直接上我githup鏈接:

https://github.com/shenahobo/TestVolley 里面libs種有個(gè)jar包.直接去clone下來(lái)就好啦.

  • 看這個(gè)文章你能知道那些?
    • 1.Volley基本概念.
    • 2.各種Request(請(qǐng)求)的簡(jiǎn)單使用.
    • 3.怎么取消Request(請(qǐng)求).
    • 4.寫出請(qǐng)求隊(duì)列的單例模式.
    • 5.設(shè)置連接的超時(shí)時(shí)間.
    • 6.具體詳情請(qǐng)看githup.

Volley簡(jiǎn)介

首先Volley是谷歌推出的,其底層是基于HttpUrlConnection 和 apche的httpClient ,其中sdk大于9(也就是2.2) 使用HttpUrlConnection,小于9 的
時(shí)候使用apche的HttpClient ,因?yàn)镠ttpUrlConnection是一個(gè)輕量級(jí)的,google對(duì)其做了許多的優(yōu)化,且在android2.2 之前有一個(gè)重大的bugd調(diào)用close()函數(shù)會(huì)影響連接池,會(huì)導(dǎo)致鏈接復(fù)用失效.而HttpClient 則是一個(gè)成熟的框架,體量相對(duì)大一些,多用于Web,并且在android6.0去除了HttpClient.

各種Request(請(qǐng)求)的簡(jiǎn)單使用.

  • StringRequest請(qǐng)求中Get請(qǐng)求
    • 1.先創(chuàng)建 RequestQueue 隊(duì)列.

                RequestQueue mQueue = Volley.newRequestQueue(getApplicationContext());
      
    • 2.創(chuàng)建StringRequest對(duì)象.

            StringRequest stringRequest = new StringRequest(Request.Method.GET, URL, new Response.Listener<String>() {
              @Override
              public void onResponse(String s) {
                  Log.i(TAG, "ThreadName: " + Thread.currentThread().getName());
                  Log.i(TAG, "onResponse: s====" + s);
                  /*Message msg = Message.obtain();
                  msg.what = SUCCESSFUL;
                  msg.obj = s;
                  mHandler.sendMessage(msg);*/
                  tvShow.setText(s);
                }
              }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError volleyError) {
                  Log.i(TAG, "onResponse: s====" + volleyError.getMessage());
                }
              });
      
    • 3.將StringRequest添加到隊(duì)列中.

            mQueue.add(stringRequest);
      
  • StringRequest中Post請(qǐng)求
    • 同樣的步驟,只是第2步不一樣,而已.

    • 1.創(chuàng)建stringRequest對(duì)象,重寫StringRequest中的getParams方法,在map集合中添加鍵值對(duì).

            StringRequest stringRequest = new StringRequest(Method.POST, url,  listener, errorListener) {  
            @Override  
            protected Map<String, String> getParams() throws AuthFailureError {  
                Map<String, String> map = new HashMap<String, String>();  
                map.put("params1", "value1");  
                map.put("params2", "value2");  
                return map;  
            }  
        };  
      
    • 2.添加到隊(duì)列中.

        mQueue.add(stringRequest);
      
  • JsonRequest的用法.
    • 1.需要注意的是:JsonRequest有兩個(gè)子類,一個(gè)JsonObjectRequest, JsonArrayRequest兩個(gè)類.

            JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, GETURL, null, new Response.Listener<JSONObject>() {
                        @Override
                        public void onResponse(JSONObject jsonObject) {
                            tvShowTwo.setText(jsonObject.toString());
                        }
                    }, new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError volleyError) {
                            tvShowTwo.setText(volleyError.getMessage());
                        }
                    });
      
    • 2.添加到隊(duì)列中.

           mQueue.add(stringRequest);  
      
  • 圖片的就不貼代碼了,需要的直接去 https://github.com/shenahobo/TestVolley

請(qǐng)求的取消.

  • Volley請(qǐng)求的的取消.
    • 1.取消單個(gè),直接用請(qǐng)求對(duì)象調(diào)用cancle()方法.

            stringRequest.cancle();
      
    • 2.取消全部 返回true 取消全部.

            mRequestQueue.cancelAll(new RequestQueue.RequestFilter()
            {
                rrturn true ;});
      
    • 3.取消設(shè)置了TAG(標(biāo)識(shí))的請(qǐng)求

            mRequestQueue.cancelAll(TAG);//取消tag為TAG的的請(qǐng)求.
      

設(shè)置請(qǐng)求的超時(shí)時(shí)間.

      //3,設(shè)置超時(shí)時(shí)間 參數(shù)含義:超時(shí)時(shí)間  重試次數(shù)  超時(shí)時(shí)間因子
      mStringRequest.setRetryPolicy(new DefaultRetryPolicy(500, 1, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

請(qǐng)求隊(duì)列的單例模式.

public class MyApplication extends Application {
private RequestQueue mRequestQueue;
private static volatile MyApplication mInstance;

@Override
public void onCreate() {
    super.onCreate();
    //得到MyApplication 的對(duì)象.
    mInstance = this;
    if (mRequestQueue == null) {
        synchronized (MyApplication.class) {
            if (mRequestQueue == null) {
                mRequestQueue = Volley.newRequestQueue(getApplicationContext());
            }
        }
    }
}

public static synchronized MyApplication getInstance() {
    return mInstance;
}

/**
 * 得到請(qǐng)求隊(duì)列
 *
 * @return 返回請(qǐng)求隊(duì)列
 */
public RequestQueue getRequestQueue() {
    return mRequestQueue;
}

/**
 * 添加到請(qǐng)求隊(duì)列
 *
 * @param req 請(qǐng)求
 * @param TAG 標(biāo)識(shí)
 * @param <T>
 */
public <T> void addRequest(Request<T> req, Object TAG) {
    if (req != null) {
        req.setTag(TAG);
        getRequestQueue().add(req);
    }
}

public <T> void add(Request<T> req) {
    if (req != null) {
        getRequestQueue().add(req);
    }
}

/**
 * 取消所有請(qǐng)求
 *
 * @param TAG 標(biāo)識(shí)
 * @param <T>
 */
public <T> void cancelRequest(Object TAG) {
    getRequestQueue().cancelAll(TAG);
}

/**
 * 取消單個(gè)請(qǐng)求
 *
 * @param req
 * @param <T>
 */
public <T> void cancle(Request<T> req) {
    if (req != null) {
        req.cancel();
    }
}

}

最后 需要注意的地方.

  • 所對(duì)應(yīng)的回調(diào),通過(guò)打Log發(fā)現(xiàn)是在主線程中的, 所以可以直接在里面更新UI.
  • 使用的時(shí)候需要添加聯(lián)網(wǎng)的權(quán)限.
  • 創(chuàng)建的Applcation類需要在清單文件中進(jìn)行配置.
  • 取消請(qǐng)求的時(shí)候,Request對(duì)象還沒有創(chuàng)建,需要進(jìn)行非空判斷,防止空指針.
  • 當(dāng)取消請(qǐng)求的時(shí)候,onResponse和onErrorResponse方法將不會(huì)執(zhí)行.
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容