# # # 1. The overview
Last time we talked about Volley,Okhttp,Retrofit which one should I choose? But does the third party network framework is more, also don’t know what to wait a few years, then may be we will change, but as this is a version of the iteration is very headache, if you want to change the better network framework cost is relatively high, today we look at how to build a network framework of the engine, on the one hand, in order to package, On the one hand, it is convenient to switch network framework.
All shared outline: 2017Android road to progress with you
Video on address: http://pan.baidu.com/s/1pKWuZrX
###2. Routine analysis
Third party web frameworks, such as Okhttp, Volley, Retrofit, etc., are often packaged as required during development. Encapsulation is to better meet the needs of our project, easy to call, this step may be indispensable, so we just need to think about how to achieve arbitrary switching network framework? It’s best if you can switch at will.
In fact, when we request the data is basically similar is to get the data and display the data, but the problem is that the network framework is different, so we just need to solve this problem. So at this time we just need to make a routine, our Activity -> our routine -> the third network framework follows our routine -> the third network framework, but will there be a problem? There may be a few issues, not a direct lineage after all, but as long as the code is extensible, it will be fine as the project progresses.
# # # 3. Implementation
A custom set of rules can be as simple as possible, or as complex as required by the project.
/** * Created by Darren on 2017/03/01 * Email: [email protected] * Description: Public void post(Context Context, String URL, Map<String, Object> params, HttpCallBack httpCallBack, boolean cache); Public void get(Context Context, String URL, Map<String, Object> params, HttpCallBack HttpCallBack, boolean cache); // Cancel request // download file // upload file // HTTPS add security certificate}Copy the code
Define your own routines HttpUtils:
/** * Created by Darren on 2017/03/01 * Email: [email protected] * Description: */ public class HttpUtils {// Context private Context mContext; Private static HttpEngine mHttpEngine = new OkHttpEngine(); // Interface address private String mUrl; Private Map<String, Object> mParams; Private Final int GET_REQUEST = 0x0011; Private Final int POST_REQUEST = 0x0022; Private int requestMethod = GET_REQUEST; private int requestMethod = GET_REQUEST; Private Boolean mCache =false; Public void exchangeEngine(HttpEngine HttpEngine){this.mhttpengine = HttpEngine; } public static initEngine(HttpEngine HttpEngine){this.mhttpengine = HttpEngine; } private HttpUtils(Context context) { this.mContext = context; mParams = new HashMap<>(); } public static HttpUtils with(Context context) {return new HttpUtils(context);
}
public HttpUtils url(String url) {
mUrl = url;
returnthis; } public void execute(HttpCallBack HttpCallBack) {if (TextUtils.isEmpty(mUrl)) {
throw new NullPointerException("Access path cannot be empty");
}
if (mRequestMethod == GET_REQUEST) {
get(mUrl, mParams, httpCallBack);
}
if(mRequestMethod == POST_REQUEST) { post(mUrl, mParams, httpCallBack); }}}Copy the code
Encapsulate a simple example OkhttpEnigne:
/** * Created by Darren on 2017/03/01 * Email: [email protected] * Description: Public class implements HttpEngine {private static OkHttpClient mOkHttpClient = new OkHttpClient(); @Override public void post(final Context context, String url, Map<String, Object> params, Final HttpCallBack HttpCallBack, final Boolean cache) {// Omit some code...... RequestBody requestBody = appendBody(params); Request request = new Request.Builder() .url(url) .tag(context) .post(requestBody) .build(); mOkHttpClient.newCall(request).enqueue( newCallback() { @Override public void onFailure(Call call, final IOException e) { executeError(httpCallBack, e); } @Override public void onResponse(Call call, Response response) throws IOException { String resultJson = response.body().string(); executeSuccessMethod(httpCallBack, resultJson); }}); Private void executeSuccessMethod(Final HttpCallBack HttpCallBack, executeSuccessMethod) final String resultJson) { try { HttpUtils.handler.post(newRunnable() {
@Override
public void run() { httpCallBack.onSucceed(resultJson); }}); } catch (Exception e) { executeError(httpCallBack, e); e.printStackTrace(); }} /** * private void executeError(final HttpCallBack HttpCallBack, final Exception e) { HttpUtils.handler.post(newRunnable() {
@Override
public void run() { httpCallBack.onError(e); }}); } @Override public void get(Context context, String url, Map<String, Object> params, final HttpCallBack httpCallBack, Boolean cache) {// omit some code...... Request.Builder requestBuilder = new Request.Builder().url(url).tag(context); Request request = requestBuilder.build(); mOkHttpClient.newCall(request).enqueue(newCallback() { @Override public void onFailure(Call call, IOException e) { httpCallBack.onError(e); } @Override public void onResponse(Call call, Response response) throws IOException { String resultJson = response.body().string(); Httputils.handler. post(new) httputils.handler.post (newRunnable() {
@Override
public void run() { httpCallBack.onSucceed(result); }}); }}); }Copy the code
We can try Retrofit on our own, but I won’t write it here, because a lot of people don’t know Retrofit very well. I would also like to start writing articles in RxJava and work my way up to Retrofit. Now that we have a default OkHttpEngine, if we need to configure or switch it, we need to customize the engine, and then switch to the current engine. Let’s see how to use it:
HttpUtils.with(context) .exchangeEngine(new RetrofitEngine()); // Switch to Retrofit engine. Url (urlconstant.city_main_page) // path.addparam ("city", mCurrentCity) // Add.cache(truePost () // post submit. Execute (new HttpCallBack<CityFragmentEntity>() {@override public void onError(Exception) E) {// Error callback} @override public void onSucceed(CityFragmentEntity result) {// The parsed object returned by result can be operated directly without Json parsing Successful callback}});Copy the code
It’s not that much of a problem but if there’s a better third-party network framework in the future we can configure the engine in the Application, and we can specify a different engine for each request, which is actually interface oriented programming, and there’s still a problem with data caching, The next issue we need to use the object-oriented thought myself to write a set of database packages, we have to on-demand customized writes the database in the external memory card, also need to consider the database encryption, Query lazy loading, Lucene auxiliary search and so on, not just in order to make the wheels but in order to better understand the principle of other database framework.
All shared outline: 2017Android road to progress with you
Video on address: http://pan.baidu.com/s/1pKWuZrX