Android中網(wǎng)絡(luò)框架的簡單封裝
老城網(wǎng)站制作公司哪家好,找創(chuàng)新互聯(lián)!從網(wǎng)頁設(shè)計、網(wǎng)站建設(shè)、微信開發(fā)、APP開發(fā)、響應(yīng)式網(wǎng)站建設(shè)等網(wǎng)站項目制作,到程序開發(fā),運營維護(hù)。創(chuàng)新互聯(lián)2013年開創(chuàng)至今到現(xiàn)在10年的時間,我們擁有了豐富的建站經(jīng)驗和運維經(jīng)驗,來保證我們的工作的順利進(jìn)行。專注于網(wǎng)站建設(shè)就選創(chuàng)新互聯(lián)。
前言
Android作為一款主要應(yīng)用在移動終端的操作系統(tǒng),訪問網(wǎng)絡(luò)是必不可少的功能。訪問網(wǎng)絡(luò),最基本的接口有:HttpUrlConnection,HttpClient,而在后續(xù)的發(fā)展中,出現(xiàn)了Volley,OkHttp,Retrofit等網(wǎng)絡(luò)封裝庫。由于各種原因,在實際的項目開發(fā)中,我們可能會需要在項目的版本迭代中,切換網(wǎng)絡(luò)框架。如果對于網(wǎng)絡(luò)框架沒有好的封裝,那么當(dāng)需要切換網(wǎng)絡(luò)框架時,可能就會有大量的遷移工作要做。
封裝網(wǎng)絡(luò)框架
在架構(gòu)設(shè)計中,面向接口和抽象,是解耦的一個重要原則。本文將基于這一原則,實現(xiàn)一個簡單的網(wǎng)絡(luò)框架封裝。
定義網(wǎng)絡(luò)訪問的接口
抽取出不同網(wǎng)絡(luò)框架的共同方法,定義成接口方法。
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); }
定義網(wǎng)絡(luò)訪問的Callback
public interface IHttpCallback { /** * 成功時的回調(diào) * * @param result */ void onSuccess(String result); /** * 失敗時的回調(diào) * * @param msg */ void onFailed(String msg); }
定義具體的接口實現(xiàn)類
分別對具體的網(wǎng)絡(luò)框架進(jìn)行接口實現(xiàn),這里以Volley和OkHttp為例
Volley的實現(xiàn)類
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的實現(xiàn)類
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的實現(xiàn)
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); } /** * 成功時的回調(diào) * * @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]; } }
返回的數(shù)據(jù)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 + '}'; } }
定義統(tǒng)一管理類
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方法中初始化網(wǎng)絡(luò)訪問
public class App extends Application { @Override public void onCreate() { super.onCreate(); // HttpHelper.init(new OkHttpLoader()); HttpHelper.init(new VolleyHttpLoader(this)); } }
后續(xù)如果需要切換網(wǎng)絡(luò)框架,只需要在這里修改就可以了。
應(yīng)用
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()); } }); } }); } }); } }
結(jié)束
這里介紹的,其實只是一個封裝的思路。基于這個思路,還可以封裝常用的圖片訪問庫等??梢宰杂赏卣埂?/p>
源碼地址:https://github.com/milovetingting/Samples/tree/master/Loader
到此這篇關(guān)于Android中網(wǎng)絡(luò)框架簡單封裝的實例方法的文章就介紹到這了,更多相關(guān)Android中網(wǎng)絡(luò)框架的簡單封裝內(nèi)容請搜索創(chuàng)新互聯(lián)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持創(chuàng)新互聯(lián)!
網(wǎng)站題目:Android中網(wǎng)絡(luò)框架簡單封裝的實例方法
網(wǎng)站網(wǎng)址:http://jinyejixie.com/article16/pggcdg.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供靜態(tài)網(wǎng)站、網(wǎng)站維護(hù)、網(wǎng)站設(shè)計、品牌網(wǎng)站制作、電子商務(wù)、網(wǎng)站策劃
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)