Android中網絡框架的簡單封裝

我的博客java

www.milovetingting.cnandroid

Android中網絡框架的簡單封裝

前言

Android做爲一款主要應用在移動終端的操做系統,訪問網絡是必不可少的功能。訪問網絡,最基本的接口有:HttpUrlConnection,HttpClient,而在後續的發展中,出現了VolleyOkHttpRetrofit等網絡封裝庫。因爲各類緣由,在實際的項目開發中,咱們可能會須要在項目的版本迭代中,切換網絡框架。若是對於網絡框架沒有好的封裝,那麼當須要切換網絡框架時,可能就會有大量的遷移工做要作。git

封裝網絡框架

在架構設計中,面向接口抽象,是解耦的一個重要原則。本文將基於這一原則,實現一個簡單的網絡框架封裝。github

定義網絡訪問的接口

抽取出不一樣網絡框架的共同方法,定義成接口方法。json

public interface IHttpLoader {

    /** * GET方式請求 * * @param url * @param params * @param callback */
    void get(String url, Map<String, Object> params, IHttpCallback callback);

    /** * POST方式請求 * * @param url * @param params * @param callback */
    void post(String url, Map<String, Object> params, IHttpCallback callback);

}
複製代碼

定義網絡訪問的Callback網絡

public interface IHttpCallback {

    /** * 成功時的回調 * * @param result */
    void onSuccess(String result);

    /** * 失敗時的回調 * * @param msg */
    void onFailed(String msg);

}
複製代碼

定義具體的接口實現類

分別對具體的網絡框架進行接口實現,這裏以Volley和OkHttp爲例架構

Volley的實現類app

public class VolleyHttpLoader implements IHttpLoader {

    private static RequestQueue mRequestQueue;

    public VolleyHttpLoader(Context context) {
        mRequestQueue = Volley.newRequestQueue(context);
    }

    @Override
    public void get(String url, Map<String, Object> params, final IHttpCallback callback) {
        StringRequest request = new StringRequest(Request.Method.GET, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String s) {
                        callback.onSuccess(s);
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                callback.onFailed(volleyError.toString());
            }
        });
        mRequestQueue.add(request);
    }

    @Override
    public void post(String url, Map<String, Object> params, final IHttpCallback callback) {
        StringRequest request = new StringRequest(Request.Method.POST, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String s) {
                        callback.onSuccess(s);
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                callback.onFailed(volleyError.toString());
            }
        });
        mRequestQueue.add(request);
    }
}
複製代碼

OkHttp的實現類框架

public class OkHttpLoader implements IHttpLoader {

    private static OkHttpClient mOkHttpClient;

    public OkHttpLoader() {
        mOkHttpClient = new OkHttpClient();
    }


    @Override
    public void get(String url, Map<String, Object> params, final IHttpCallback callback) {
        Request request = new Request.Builder().url(url).build();
        mOkHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                callback.onFailed(e.toString());
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                if (response.isSuccessful()) {
                    String result = response.body().string();
                    callback.onSuccess(result);
                } else {
                    callback.onFailed(response.message());
                }
            }
        });
    }

    @Override
    public void post(String url, Map<String, Object> params, final IHttpCallback callback) {
        RequestBody requestBody = appendBody(params);
        Request request = new Request.Builder().post(requestBody).url(url).build();
        mOkHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                callback.onFailed(e.toString());
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                if (response.isSuccessful()) {
                    String result = response.body().string();
                    callback.onSuccess(result);
                } else {
                    callback.onFailed(response.message());
                }
            }
        });
    }

    private RequestBody appendBody(Map<String, Object> params) {
        FormBody.Builder body = new FormBody.Builder();
        if (params == null || params.isEmpty()) {
            return body.build();
        }
        for (Map.Entry<String, Object> entry : params.entrySet()) {
            body.add(entry.getKey(), entry.getValue().toString());
        }
        return body.build();
    }
}
複製代碼

定義Callback的實現

public abstract class HttpCallback<Result> implements IHttpCallback {

    @Override
    public void onSuccess(String result) {
        Gson gson = new Gson();
        Class<?> clazz = analysisClazzInfo(this);
        Result resultObj = (Result) gson.fromJson(result, clazz);
        onSuccess(resultObj);
    }

    /** * 成功時的回調 * * @param result */
    public abstract void onSuccess(Result result);

    private Class<?> analysisClazzInfo(Object object) {
        Type genType = object.getClass().getGenericSuperclass();
        Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
        return (Class<?>) params[0];
    }
}
複製代碼

返回的數據Bean

public class Data {

    private int errorCode;
    private String errorMsg;
    private List<DataBean> data;

    public int getErrorCode() {
        return errorCode;
    }

    public void setErrorCode(int errorCode) {
        this.errorCode = errorCode;
    }

    public String getErrorMsg() {
        return errorMsg;
    }

    public void setErrorMsg(String errorMsg) {
        this.errorMsg = errorMsg;
    }

    public List<DataBean> getData() {
        return data;
    }

    public void setData(List<DataBean> data) {
        this.data = data;
    }

    public static class DataBean {

        private int courseId;
        private int id;
        private String name;
        private int order;
        private int parentChapterId;
        private boolean userControlSetTop;
        private int visible;
        private List<?> children;

        public int getCourseId() {
            return courseId;
        }

        public void setCourseId(int courseId) {
            this.courseId = courseId;
        }

        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public int getOrder() {
            return order;
        }

        public void setOrder(int order) {
            this.order = order;
        }

        public int getParentChapterId() {
            return parentChapterId;
        }

        public void setParentChapterId(int parentChapterId) {
            this.parentChapterId = parentChapterId;
        }

        public boolean isUserControlSetTop() {
            return userControlSetTop;
        }

        public void setUserControlSetTop(boolean userControlSetTop) {
            this.userControlSetTop = userControlSetTop;
        }

        public int getVisible() {
            return visible;
        }

        public void setVisible(int visible) {
            this.visible = visible;
        }

        public List<?> getChildren() {
            return children;
        }

        public void setChildren(List<?> children) {
            this.children = children;
        }

        @Override
        public String toString() {
            return "DataBean{" +
                    "courseId=" + courseId +
                    ", id=" + id +
                    ", name='" + name + '\'' +
                    ", order=" + order +
                    ", parentChapterId=" + parentChapterId +
                    ", userControlSetTop=" + userControlSetTop +
                    ", visible=" + visible +
                    ", children=" + children +
                    '}';
        }
    }

    @Override
    public String toString() {
        return "Data{" +
                "errorCode=" + errorCode +
                ", errorMsg='" + errorMsg + '\'' +
                ", data=" + data +
                '}';
    }

}
複製代碼

定義統一管理類

public class HttpHelper implements IHttpLoader {

    private static IHttpLoader mHttpLoader;

    private HttpHelper() {

    }

    public static void init(IHttpLoader httpLoader) {
        mHttpLoader = httpLoader;
    }

    public static HttpHelper obtain() {
        return HttpHelperHolder.INSTANCE;
    }

    static class HttpHelperHolder {
        private static HttpHelper INSTANCE = new HttpHelper();
    }

    @Override
    public void get(String url, Map<String, Object> params, IHttpCallback callback) {
        mHttpLoader.get(url, params, callback);
    }

    @Override
    public void post(String url, Map<String, Object> params, IHttpCallback callback) {
        mHttpLoader.post(url, params, callback);
    }
}
複製代碼

在Application中初始化

定義一個繼承自Application的類,在onCreate方法中初始化網絡訪問ide

public class App extends Application {

    @Override
    public void onCreate() {
        super.onCreate();
// HttpHelper.init(new OkHttpLoader());
        HttpHelper.init(new VolleyHttpLoader(this));
    }
}
複製代碼

後續若是須要切換網絡框架,只須要在這裏修改就能夠了。

應用

public class MainActivity extends AppCompatActivity {

    private static final String URL_HTTP = "https://www.wanandroid.com/wxarticle/chapters/json";

    private ImageView mIv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mTv = findViewById(R.id.tv);

        findViewById(R.id.btn_get).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                HttpHelper.obtain().get(URL_HTTP, null, new HttpCallback<Data>() {
                    @Override
                    public void onFailed(final String msg) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                mTv.setText(msg);
                            }
                        });
                    }

                    @Override
                    public void onSuccess(final Data data) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                mTv.setText(data.toString());
                            }
                        });
                    }
                });
            }
        });

    }
}
複製代碼

結束

這裏介紹的,其實只是一個封裝的思路。基於這個思路,還能夠封裝經常使用的圖片訪問庫等。能夠自由拓展。

源碼

源碼地址:github.com/milovetingt…

相關文章
相關標籤/搜索