Android Volley二次封裝

在網上搜索了幾遍關於android volley的二次封裝。大多都是仍然沒有脫離使用時的三個步驟
1. mQueue = Volley.newRequestQueue(context);
2. JsonObjectRequest request = new JsonObjectRequest(method, url, requestBody, listener, errorListener) 實例化
3. mQueue.add(request)

這樣始終用起來不方便,不能一個方法就解決網絡請求。

最開始是設想把這三個步驟封裝在一個方法中,那麼這樣就會出現一個問題:如果一個activity多次調用的話,那麼就會多次執行Volley.newRequestQueue(context);,結果是產生了多個mQueue,導致Volley原本設計好的消息隊列失去了價值,且降低了效率。

於是,我將mQueue = Volley.newRequestQueue(context);使用了單例模式,確保每次mQueue.add(request)的mQueue都是同一個。

源碼如下:

package com.goldmidai.android.encapsulations;

import java.util.HashMap;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONObject;

import android.content.Context;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;

import com.android.volley.AuthFailureError;
import com.android.volley.Request.Method;
import com.android.volley.RequestQueue;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.goldmidai.android.network.ConnectionConfig;
import com.goldmidai.android.utils.PreferencesUtils;
import com.lucio.library.util.Util;
import com.lucio.library.widget.SALoadingDialog;

public class MVollyRequest {
    private RequestQueue mQueue;
    private static MVollyRequest mVollyRequest;
    private static HashMap<String, String> headers;
    public static int REQUEST_GET = 0;
    public static int REQUEST_POST = 1;

    private MVollyRequest(Context context) {
        if (mQueue == null) {
            mQueue = Volley.newRequestQueue(context);
        }
        headers = new HashMap<String, String>();
        headers.put("Content-Type", "application/json;charset=utf-8");
        headers.put("os", "Android");
    }

    public static MVollyRequest getInstance(Context context) {
        if (mVollyRequest == null) {
            mVollyRequest = new MVollyRequest(context);

        }
        return mVollyRequest;
    }

    /**
     * stringRequest requestMethod GET Default
     * 
     * @param url
     */
    /*
     * public void stringRequest(String url, Listener<String> listener,
     * ErrorListener errorListener) { StringRequest request = new
     * StringRequest(url,listener, errorListener) {
     * 
     * @Override public Map<String, String> getHeaders() throws AuthFailureError
     * {
     * 
     * return headers; } };
     * 
     * mQueue.add(request); }
     */
    /**
     * stringRequest
     * 
     * @param requestMethod
     * @param url
     */
    /*
     * public void stringRequest(int requestMethod, String url, Listener<String>
     * listener, ErrorListener errorListener,final Map<String,String> map) { if
     * (requestMethod == REQUEST_GET) {
     * stringRequest(url,listener,errorListener); } else if (requestMethod ==
     * REQUEST_POST) { StringRequest request = new StringRequest(Method.POST,
     * url,listener,errorListener) {
     * 
     * @Override protected Map<String, String> getParams() throws
     * AuthFailureError { return map; }
     * 
     * @Override public Map<String, String> getHeaders() throws AuthFailureError
     * {
     * 
     * return headers; } }; mQueue.add(request); } }
     */
    /**
     * jsonObjectRequest
     * 
     * Creates a new request.
     * 
     * @param method
     *            the HTTP method to use
     * @param url
     *            URL to fetch the JSON from
     * @param requestBody
     *            A {@link String} to post with the request. Null is allowed and
     *            indicates no parameters will be posted along with request.
     * @param listener
     *            Listener to receive the JSON response
     * @param errorListener
     *            Error listener, or null to ignore errors.
     */
    public void jsonObjectRequest(int method, String url, String requestBody,
            Listener<JSONObject> listener, ErrorListener errorListener) {
        JsonObjectRequest request = new JsonObjectRequest(method, url,
                requestBody, listener, errorListener) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {

                return headers;
            }
        };
        mQueue.add(request);
    }

    /**
     * jsonObjectRequest
     * 
     * Creates a new request.
     * 
     * @param url
     *            URL to fetch the JSON from
     * @param listener
     *            Listener to receive the JSON response
     * @param errorListener
     *            Error listener, or null to ignore errors.
     */
    public void jsonObjectRequest(String url, Listener<JSONObject> listener,
            ErrorListener errorListener) {
        jsonObjectRequest(Method.GET, url, null, listener, errorListener);
    }

    /**
     * jsonObjectRequest
     * 
     * Creates a new request.
     * 
     * @param method
     *            the HTTP method to use
     * @param url
     *            URL to fetch the JSON from
     * @param listener
     *            Listener to receive the JSON response
     * @param errorListener
     *            Error listener, or null to ignore errors.
     */
    public void jsonObjectRequest(int method, String url,
            Listener<JSONObject> listener, ErrorListener errorListener) {
        jsonObjectRequest(method, url, null, listener, errorListener);
    }

    /**
     * jsonArrayRequest
     * 
     * Creates a new request.
     * 
     * @param method
     *            the HTTP method to use
     * @param url
     *            URL to fetch the JSON from
     * @param requestBody
     *            A {@link String} to post with the request. Null is allowed and
     *            indicates no parameters will be posted along with request.
     * @param listener
     *            Listener to receive the JSON response
     * @param errorListener
     *            Error listener, or null to ignore errors.
     */
    /*
     * public void jsonArrayRequest(int method, String url, String requestBody,
     * Listener<JSONArray> listener, ErrorListener errorListener) {
     * JsonArrayRequest request = new JsonArrayRequest(method, url, requestBody,
     * listener, errorListener) {
     * 
     * @Override public Map<String, String> getHeaders() throws AuthFailureError
     * {
     * 
     * return headers; } }; mQueue.add(request); }
     */
    /**
     * jsonArrayRequest
     * 
     * Creates a new request.
     * 
     * @param url
     *            URL to fetch the JSON from
     * @param listener
     *            Listener to receive the JSON response
     * @param errorListener
     *            Error listener, or null to ignore errors.
     */
    /*
     * public void jsonArrayRequest(String url, Listener<JSONArray> listener,
     * ErrorListener errorListener) { jsonArrayRequest(Method.GET, url, null,
     * listener, errorListener); }
     */
    /**
     * jsonArrayRequest
     * 
     * Creates a new request.
     * 
     * @param method
     *            the HTTP method to use
     * @param url
     *            URL to fetch the JSON from
     * @param listener
     *            Listener to receive the JSON response
     * @param errorListener
     *            Error listener, or null to ignore errors.
     */
    /*
     * public void jsonArrayRequest(int method, String url, Listener<JSONArray>
     * listener, ErrorListener errorListener) { jsonArrayRequest(Method.GET,
     * url, null, listener, errorListener); }
     */
}

代碼中將header也封裝其中。(由於項目原因:註釋掉了除jsonObjectRequest之外的請求)

方法調用:

private void requestLogin(){
        LoginReqEntity loginEntity = new LoginReqEntity();
        loginEntity.setMobile(loginPhone);
        loginEntity.setLoginPassword(lPwd);

        MVollyRequest.getInstance(baseActivity).jsonObjectRequest(MVollyRequest.REQUEST_POST, ConnectionType.LOGIN_URL,
                ObjectJsonMapper.toJson(loginEntity), new Listener<JSONObject>() {

                    @Override
                    public void onResponse(JSONObject response) {
                    HttpResult httpResult = (HttpResult) ObjectJsonMapper.parseJsonObject(response.toString(), HttpResult.class);
                    }
                }, new ErrorListener() {

                    @Override
                    public void onErrorResponse(VolleyError error) {

                    }
                });
    }

在網上看到有人特意爲分離解析 JsonObject 做一個bean傳參。
大致看了一下覺得寫的複雜了,因爲這裏正好用到Gson,所以就直接用Gson的內置方法(gson.toObject | gson.fromObject(json,class))。

這裏的好處是脫離了需要使用三個步驟,使整個網絡請求方法更加面向對象。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章