• Android,适合Restful网络请求封装


    借助volley、Gson类库。

    优点

    网络请求集中处理,返回值直接为预期的对象,不需要手动反序列,提高效率,使用时建立好model类即可。

    使用效果

    DataProess.Request(true, context,
        Request.Method.GET,
        DataApis.CTenantAdsUrl + "73213f9c-e695-420d-9398-2cc9fc2b8492",
        null,
        new DataCallback<List<TenantAdsModel>>() {
            //Java的泛型会类型擦除,只能在外部直接传递进去。虽然内部可以通过子类new泛型对象方式,但是这种实现感觉不够优美。Gson使用了反射进行泛型类型获取,之后改进可以考虑。非List返回类型可以重载getClassHelper()直接传递类型class。
            @Override
            public Type getTypeHelper() {
                return new TypeToken<List<TenantAdsModel>>() {
                }.getType();
            }
    
            @Override
            public void CallBack(List<TenantAdsModel> data) {
                //后续操作
                }
            }
    
            @Override
            public void ErrorCallBack(int statusCode, String s) {
                alertDialog.show();
            }
    
            @Override
            public void FinallyCallBack() {
                //自写进度控制Util,可以多次show,在对应次数hide后或超时才隐藏。这样即可不用考虑多个数据请求的问题,都完成才会消除进度条。
                ProgressUtil.hide();
            }
        }
    );
    

    实现

    首先是DataCallback:

    public class DataCallback<DataType> {
        final static GsonBuilder builder = new GsonBuilder();
    
        public final <T> T ConvertData(String oData, Type type) {
            Gson gson = builder.setDateFormat("yyyy-MM-dd'T'HH:mm:ss").create();
    
            return gson.fromJson(oData, type);
        }
    
        public final <T> T ConvertData(String oData, Class<T> cl) {
            Gson gson = builder.setDateFormat("yyyy-MM-dd'T'HH:mm:ss").create();
    
            return gson.fromJson(oData, cl);
        }
    
        public Type getTypeHelper() {
            return null;
        }
    
        public Class<DataType> getClassHelper() {
            return null;
        }
    
        public void StringCallBack(String data) {
            Type type = getTypeHelper();
            Class<DataType> cl = getClassHelper();
            DataType dt = null;
            try {
                if (type != null) dt = ConvertData(data, type);
                if (cl != null) dt = ConvertData(data, cl);
                if (dt != null) {
                    CallBack(dt);
                } else {
                    ErrorCallBack(-3, null);
                }
            } catch (Exception ex) {
                ErrorCallBack(-2, "callBack");
            }
        }
    
        public void CallBack(DataType data) {
    
        }
    
        public void ErrorCallBack(int statusCode, String s) {
    
        }
    
        public void FinallyCallBack() {
    
        }
    }
    

    核心处理类:
    服务器端采用OAuth Password Flow鉴权,使用Authorization头就好。鉴权失败事件使用的是自写的事件机制

    public class DataProess {
        final static String AppToken = "Basic VXBwV2luQXBwOjF5N09jSUN4d3F5YUNSVWE3dVVBeFc5c3AzdVRubU9JbW9IY3JocDdUOWM=";
        final static GsonBuilder gsonBuilder = new GsonBuilder();
        static LruCache<String, Object> lruCache = new LruCache<String, Object>(20);
        static String UserToken = "";
    
        public static EventTrans<String> AuthFailed = new EventTrans<String>();
    
        public static String getUserToken() {
            return UserToken;
        }
    
        public static void setUserToken(String userToken) {
            UserToken = userToken;
        }
    
        public void ClearCache() {
            lruCache = new LruCache<String, Object>(20);
        }
    
        public static void Request(
                final boolean useCache,
                final Context context,
                final int method,
                final String url,
                final Object data,
                final DataCallback dc) {
            RequestQueue requestQueue = Volley.newRequestQueue(context);
    
            if (useCache) {
                String cachedata = (String) lruCache.get(method + url);
                if (cachedata != null) {
                    dc.StringCallBack(cachedata);
                    dc.FinallyCallBack();
                    return;
                }
            }
            final StringRequest stringRequest = new StringRequest(
                    method,
                    url,
                    new Response.Listener<String>() {
                        @Override
                        public void onResponse(String response) {
                            if (useCache) lruCache.put(method + url, response);
                            dc.StringCallBack(response);
                            dc.FinallyCallBack();
                        }
                    },
                    new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError arg0) {
                            System.out.println("sorry,Error " + arg0.toString());
                            int sc = -1;
                            if (arg0.networkResponse != null) {
                                sc = arg0.networkResponse.statusCode;
                                if (sc == 401) {
                                    UserToken = "";
                                    AuthFailed.trigger(this, null);
                                }
    
                                try {
                                    String data = new String(arg0.networkResponse.data,
                                            HttpHeaderParser.parseCharset(arg0.networkResponse.headers));
                                    System.out.println("sorry,Error " + data);
                                } catch (UnsupportedEncodingException e) {
                                    e.printStackTrace();
                                }
                            }
                            dc.ErrorCallBack(sc, arg0.toString());
                            dc.FinallyCallBack();
                        }
                    }
            ) {
                @Override
                public Map<String, String> getHeaders() throws AuthFailureError {
                    Map<String, String> params = new HashMap<String, String>();
                    if (StringUtil.isEmpty(UserToken)) {
                        params.put("Authorization", AppToken);
                    } else {
                        params.put("Authorization", UserToken);
                    }
                    return params;
                }
    
                @Override
                public String getBodyContentType() {
                    return "application/json";
                }
    
                @Override
                public byte[] getBody() throws AuthFailureError {
                    Gson gson = gsonBuilder.setDateFormat("yyyy-MM-dd'T'HH:mm:ss").create();
    
                    String str = gson.toJson(data);
                    if (StringUtil.isEmpty(str)) return null;
                    return str.getBytes();
                }
            };
            requestQueue.add(stringRequest);
        }
    }
    
  • 相关阅读:
    IT职场求生法则
    设计模式六大原则
    非win7系统访问win7系统发布的网站
    C#自定义导出Excel
    js操作table元素,表格的行列新增、删除汇集
    一个真正合格的程序员应该具备的素质
    项目心得
    项目心得1
    Spring boot 使用profile完成不同环境的maven打包功能
    关于std容器类的内存使用
  • 原文地址:https://www.cnblogs.com/zhang740/p/3934885.html
Copyright © 2020-2023  润新知