AI智能
改变未来

Android 网络请求框架(二) Volley工具类的封装

上一篇给大家讲解了Volley的使用,因为重复代码比较多,这篇给大家简单的吧Volley封装一下.方便以后使用

  • 创建VolleyRequestUtil工具类
  • StringRequest封装
  • JsonObjectRequest GET封装
  • JsonObjectRequest POST封装
  • ImageRequest封装
  • ImageLoader封装
  • 完整代码:

创建VolleyRequestUtil工具类

实现单利模式,保证实例唯一化:

public class VolleyRequestUtil {private VolleyRequestUtil(){}private static volatile  VolleyRequestUtil mVolleyRequestUtil;private static Context mContext;private  RequestQueue requestQueue;public static VolleyRequestUtil getInstance(Context context){if (mVolleyRequestUtil == null) {synchronized (VolleyRequestUtil.class){if (mVolleyRequestUtil == null) {mContext = context;mVolleyRequestUtil = new VolleyRequestUtil();}}}return mVolleyRequestUtil;}........}

StringRequest封装

/**** @param url   用于请求文本接口* @param volleyStringInterface 用于实现请求接口*/public void StringRequest(String url, VolleyStringInterface volleyStringInterface){getVolley();StringRequest stringRequest = new StringRequest(url, volleyStringInterface.onStringResponse(), volleyStringInterface.onErr());requestQueue.add(stringRequest);}

VolleyStringInterface接口

/*** 文本实现接口*/public interface VolleyStringInterface{public Response.Listener<String> onStringResponse();public Response.ErrorListener onErr();}

getVolley()方法

//获取RequestQueue对象private void getVolley(){if (requestQueue == null) {requestQueue = Volley.newRequestQueue(mContext);}}

使用:

//参数一:文本接口//参数二:VolleyStringInterface接口实例VolleyRequestUtil.getInstance(this).StringRequest(STRINGREQUEST_URL, new VolleyRequestUtil.VolleyStringInterface() {@Overridepublic Response.Listener<String> onStringResponse() {//这里返回值是什么就new什么return new Response.Listener<String>() {@Overridepublic void onResponse(String response) {Log.i(\"VolleyStringRequest\",response);}};}@Overridepublic Response.ErrorListener onErr() {//  //这里返回值是什么就new什么return new Response.ErrorListener() {@Overridepublic void onErrorResponse(VolleyError error) {Log.i(\"VolleyStringRequest\",error.getMessage());}};}});

注释都有所讲解,请详细阅读注释:

来看看Log吧:

JsonObjectRequest GET封装

/**** @param url   请求GET接口* @param volleyListenerInterface*/public void GETJsonObjectRequest(String url, VolleyListenerInterface volleyListenerInterface){getVolley();JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(url,null,volleyListenerInterface.onResponse(),volleyListenerInterface.onErr());requestQueue.add(jsonObjectRequest);}

VolleyListenerInterface接口:

/*** JsonObject实现接口*/public interface VolleyListenerInterface {/**** @return  返回JSONObject接口对象*/public abstract Response.Listener<JSONObject>  onResponse();/**** @return 报错提示*/public abstract Response.ErrorListener  onErr();}

使用:

VolleyRequestUtil.getInstance(this).GETJsonObjectRequest(\"http://www.weather.com.cn/data/city3jdata/china.html\", new VolleyRequestUtil.VolleyListenerInterface() {@Overridepublic Response.Listener<JSONObject> onResponse() {//这里需要什么就new什么return new Response.Listener<JSONObject>() {@Overridepublic void onResponse(JSONObject response) {Log.i(\"onResponse\", response.toString());}};}@Overridepublic Response.ErrorListener onErr() {//这里需要什么就new什么return new Response.ErrorListener() {@Overridepublic void onErrorResponse(VolleyError error) {Log.i(\"onErrorResponse\", error.getMessage());}};}});

来康康效果吧:

JsonObjectRequest POST封装

/**** @param url   请求POST接口* @param hashMap   请求POST参数* @param volleyListenerInterface*/public void POSTJsonObjectRequest(String url, final HashMap hashMap, VolleyListenerInterface volleyListenerInterface){getVolley();JSONObject jsonObject = new JSONObject(hashMap);JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST,url,jsonObject,volleyListenerInterface.onResponse(),volleyListenerInterface.onErr()){@Overrideprotected Map<String, String> getParams() throws AuthFailureError {hashMap.put(\"Accept\", \"application/json\");hashMap.put(\"Content-Type\", \"application/json; charset=UTF-8\");return hashMap;}};requestQueue.add(jsonObjectRequest);}

VolleyListenerInterface接口:

 /*** JsonObject实现接口*/public interface VolleyListenerInterface {/**** @return  返回JSONObject接口对象*/public abstract Response.Listener<JSONObject>  onResponse();/**** @return 报错提示*/public abstract Response.ErrorListener  onErr();}

使用:

HashMap<String, String> hashMap = new HashMap<>();hashMap.put(\"app_key\",\"74D2E724FE2B69EF7EA3F38E9400CF71\");VolleyRequestUtil.getInstance(this).POSTJsonObjectRequest(\"POST接口\", hashMap, new VolleyRequestUtil.VolleyListenerInterface() {@Overridepublic Response.Listener<JSONObject> onResponse() {return new Response.Listener<JSONObject>() {@Overridepublic void onResponse(JSONObject response) {}};}@Overridepublic Response.ErrorListener onErr() {return new Response.ErrorListener() {@Overridepublic void onErrorResponse(VolleyError error) {}};}});

ImageRequest封装

/**** @param url   请求图片接口* @param maxWidth  解码此位图的最大宽度,或0表示无                                参数分别用于指定允许图片最大的宽度和高度,如果指定的网络图片的宽度或高度大于这里的最大值,*                                                                                  则会对图片进行压缩,指定成0的话就表示不管图片有多大,都不会进行压缩* @param maxHeigth 解码此位图的最大高度,或为零表示无* @param rgb   设置颜色属性  Bitmap.Config.ARGB_8888 属性最好* @param volleyImageInterface 图片正确错误接口*/public void ImageRequest(String url, int maxWidth, int maxHeigth, Bitmap.Config rgb, VolleyImageInterface volleyImageInterface){getVolley();ImageRequest imageRequest = new ImageRequest(url,volleyImageInterface.onBitmap(),maxWidth,maxHeigth,rgb,volleyImageInterface.onErr());requestQueue.add(imageRequest);}

VolleyImageInterface 实现接口:

/***  Bitmap实现接口*/public interface VolleyImageInterface {/**** @return  返回Bitmap图片*/public abstract  Response.Listener<Bitmap> onBitmap();/**** @return  报错*/public abstract Response.ErrorListener onErr();}

使用:

VolleyRequestUtil.getInstance(this).ImageRequest(\"http://api.map.baidu.com/images/weather/day/zhenyu.png\", 0, 0, Bitmap.Config.ARGB_8888, new VolleyRequestUtil.VolleyImageInterface() {@Overridepublic Response.Listener<Bitmap> onBitmap() {return new Response.Listener<Bitmap>() {@Overridepublic void onResponse(Bitmap response) {mImage.setImageBitmap(response);}};}@Overridepublic Response.ErrorListener onErr() {return new Response.ErrorListener() {@Overridepublic void onErrorResponse(VolleyError error) {Log.i(\"onErrorResponse\", error.getMessage());}};}});

ImageLoader封装

/**** @param view      设置的ImageView* @param uri       加载图片的路径* @param defaultImageResId   未加载出图片时的图片* @param errorImageResId       加载报错时的图片* @param maxWidth  图像的最大宽度* @param maxHeight 图像的最大高度* @param volleyImageLoaderLolderInterface  缓存接口*/public  void ImageLoader(ImageView view ,String uri, int defaultImageResId, final int errorImageResId ,int maxWidth, int maxHeight, VolleyImageLoaderLolderInterface volleyImageLoaderLolderInterface){getVolley();ImageLoader imageLoader = new ImageLoader(requestQueue, volleyImageLoaderLolderInterface.onCache());ImageLoader.ImageListener imageListener = ImageLoader.getImageListener(view, defaultImageResId, errorImageResId);imageLoader.get(uri, imageListener,maxWidth,maxHeight);}/**** @param view      设置的ImageView* @param uri       加载图片的路径* @param defaultImageResId   未加载出图片时的图片* @param errorImageResId       加载报错时的图片* @param volleyImageLoaderLolderInterface  缓存接口*/public  void ImageLoader(ImageView view ,String uri, int defaultImageResId, final int errorImageResId  ,VolleyImageLoaderLolderInterface volleyImageLoaderLolderInterface){getVolley();ImageLoader imageLoader = new ImageLoader(requestQueue, volleyImageLoaderLolderInterface.onCache());ImageLoader.ImageListener imageListener = ImageLoader.getImageListener(view, defaultImageResId, errorImageResId);imageLoader.get(uri, imageListener);}

VolleyImageLoaderLolderInterface接口:

/***  ImageLolder实现可缓存图片接口*/public interface VolleyImageLoaderLolderInterface {/**** @return 缓存* ImageLoader.ImageCache 返回2个参数   getBitmap(String url)    参数一:返回当前请求的接口*                                      putBitmap(String url, Bitmap bitmap)    参数一:返回当前请求的接口,参数二:返回当前Bitmap对象*                                      主要用来进行缓存*/public abstract ImageLoader.ImageCache onCache();}

使用:

VolleyRequestUtil.getInstance(this).ImageLoader(image2,\"http://api.map.baidu.com/images/weather/night/duoyun.png\",R.drawable.ic_launcher_foreground,R.drawable.ic_launcher_background,new VolleyRequestUtil.VolleyImageLoaderLolderInterface() {@Overridepublic ImageLoader.ImageCache onCache() {return new ImageLoader.ImageCache() {@Overridepublic Bitmap getBitmap(String url) {return null;}@Overridepublic void putBitmap(String url, Bitmap bitmap) {}};}});

完整代码:

package demo.ht.com.volley.http;import android.content.Context;import android.graphics.Bitmap;import android.widget.ImageView;import com.android.volley.AuthFailureError;import com.android.volley.DefaultRetryPolicy;import com.android.volley.Request;import com.android.volley.RequestQueue;import com.android.volley.Response;import com.android.volley.VolleyError;import com.android.volley.toolbox.ImageLoader;import com.android.volley.toolbox.ImageRequest;import com.android.volley.toolbox.JsonObjectRequest;import com.android.volley.toolbox.StringRequest;import com.android.volley.toolbox.Volley;import org.json.JSONObject;import java.util.HashMap;import java.util.Map;/*** Created by szj 20200714*  implementation \'com.android.volley:volley:1.1.1\'*/public class VolleyRequestUtil {private VolleyRequestUtil(){}private static volatile  VolleyRequestUtil mVolleyRequestUtil;private static Context mContext;private  RequestQueue requestQueue;public static VolleyRequestUtil getInstance(Context context){if (mVolleyRequestUtil == null) {synchronized (VolleyRequestUtil.class){if (mVolleyRequestUtil == null) {mContext = context;mVolleyRequestUtil = new VolleyRequestUtil();}}}return mVolleyRequestUtil;}/**** @param url   请求GET接口* @param volleyListenerInterface*/public void GETJsonObjectRequest(String url, VolleyListenerInterface volleyListenerInterface){getVolley();JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(url,null,volleyListenerInterface.onResponse(),volleyListenerInterface.onErr());requestQueue.add(jsonObjectRequest);}/**** @param url   用于请求文本接口* @param volleyStringInterface 用于实现请求接口*/public void StringRequest(String url, VolleyStringInterface volleyStringInterface){getVolley();StringRequest stringRequest = new StringRequest(url, volleyStringInterface.onStringResponse(), volleyStringInterface.onErr());requestQueue.add(stringRequest);}/***  获取RequestQueue对象*/private void getVolley(){if (requestQueue == null) {requestQueue = Volley.newRequestQueue(mContext);}}/**** @param url   请求POST接口* @param hashMap   请求POST参数* @param volleyListenerInterface*/public void POSTJsonObjectRequest(String url, final HashMap hashMap, VolleyListenerInterface volleyListenerInterface){getVolley();JSONObject jsonObject = new JSONObject(hashMap);JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST,url,jsonObject,volleyListenerInterface.onResponse(),volleyListenerInterface.onErr()){@Overrideprotected Map<String, String> getParams() throws AuthFailureError {hashMap.put(\"Accept\", \"application/json\");hashMap.put(\"Content-Type\", \"application/json; charset=UTF-8\");return hashMap;}};requestQueue.add(jsonObjectRequest);}/**** @param url   请求图片接口* @param maxWidth  解码此位图的最大宽度,或0表示无                                参数分别用于指定允许图片最大的宽度和高度,如果指定的网络图片的宽度或高度大于这里的最大值,*                                                                                  则会对图片进行压缩,指定成0的话就表示不管图片有多大,都不会进行压缩* @param maxHeigth 解码此位图的最大高度,或为零表示无* @param rgb   设置颜色属性  Bitmap.Config.ARGB_8888 属性最好* @param volleyImageInterface 图片正确错误接口*/public void ImageRequest(String url, int maxWidth, int maxHeigth, Bitmap.Config rgb, VolleyImageInterface volleyImageInterface){getVolley();ImageRequest imageRequest = new ImageRequest(url,volleyImageInterface.onBitmap(),maxWidth,maxHeigth,rgb,volleyImageInterface.onErr());requestQueue.add(imageRequest);}/**** @param view      设置的ImageView* @param uri       加载图片的路径* @param defaultImageResId   未加载出图片时的图片* @param errorImageResId       加载报错时的图片* @param maxWidth  图像的最大宽度* @param maxHeight 图像的最大高度* @param volleyImageLoaderLolderInterface  缓存接口*/public  void ImageLoader(ImageView view ,String uri, int defaultImageResId, final int errorImageResId ,int maxWidth, int maxHeight, VolleyImageLoaderLolderInterface volleyImageLoaderLolderInterface){getVolley();ImageLoader imageLoader = new ImageLoader(requestQueue, volleyImageLoaderLolderInterface.onCache());ImageLoader.ImageListener imageListener = ImageLoader.getImageListener(view, defaultImageResId, errorImageResId);imageLoader.get(uri, imageListener,maxWidth,maxHeight);}/**** @param view      设置的ImageView* @param uri       加载图片的路径* @param defaultImageResId   未加载出图片时的图片* @param errorImageResId       加载报错时的图片* @param volleyImageLoaderLolderInterface  缓存接口*/public  void ImageLoader(ImageView view ,String uri, int defaultImageResId, final int errorImageResId  ,VolleyImageLoaderLolderInterface volleyImageLoaderLolderInterface){getVolley();ImageLoader imageLoader = new ImageLoader(requestQueue, volleyImageLoaderLolderInterface.onCache());ImageLoader.ImageListener imageListener = ImageLoader.getImageListener(view, defaultImageResId, errorImageResId);imageLoader.get(uri, imageListener);}/***  Bitmap实现接口*/public interface VolleyImageInterface {/**** @return  返回Bitmap图片*/public abstract  Response.Listener<Bitmap> onBitmap();/**** @return  报错*/public abstract Response.ErrorListener onErr();}/***  ImageLolder实现可缓存图片接口*/public interface VolleyImageLoaderLolderInterface {/**** @return 缓存* ImageLoader.ImageCache 返回2个参数   getBitmap(String url)    参数一:返回当前请求的接口*                                      putBitmap(String url, Bitmap bitmap)    参数一:返回当前请求的接口,参数二:返回当前Bitmap对象*                                      主要用来进行缓存*/public abstract ImageLoader.ImageCache onCache();}/*** JsonObject实现接口*/public interface VolleyListenerInterface {/**** @return  返回JSONObject接口对象*/public abstract Response.Listener<JSONObject>  onResponse();/**** @return 报错提示*/public abstract Response.ErrorListener  onErr();}/*** 文本实现接口*/public interface VolleyStringInterface{public Response.Listener<String> onStringResponse();public Response.ErrorListener onErr();}}

封装的可能没有个别大佬完善,但我已经尽力了,要有更高见解,请在评论区留言哦~~

Git链接: langyangyang.

赞(0) 打赏
未经允许不得转载:爱站程序员基地 » Android 网络请求框架(二) Volley工具类的封装