Volley与XUtils网络请求使用对比,心得,两者基本使用

时间:2023-03-09 18:03:05
Volley与XUtils网络请求使用对比,心得,两者基本使用

之前一直使用的Volley作为网络请求框架,它是Google 在2013年的I/O大会 上,发布的。Volley是Android平台上的网络通信库,能使网络通信更快,更简单,更健壮,同时扩展性很强。在用它之前我进行了简单的封装,因为Volley默认的请求线程生命周期伴随着Activity的周期,这有时并不能满足项目需要,so上代码:

     <span style="font-size:14px;"><span style="font-size:14px;">public class VolleyController extends Application
{
/*
* 网络请求TAG标签
*/
public static final String TAG = "VolleyPatterns"; /*
* 创建请求队列
*/
private RequestQueue requestQueue; /*
* 创建单例模式对象
*/
private static VolleyController volleyController; private Context context; @Override
public void onCreate()
{
super.onCreate();
volleyController = this;
} /**
* 获得VolleyConroller的单例对象
*/
public static synchronized VolleyController getInstance()
{
if (volleyController != null)
{ return volleyController;
}
else
{
return volleyController = new VolleyController();
}
} /**
* 获得消息队列对象
*
* @return
*/
public RequestQueue getRequestQueue(Context context)
{
this.context = context;
if (requestQueue == null)
{
synchronized (VolleyController.class)
{
if (requestQueue == null)
{
// LogUtils.i(TAG, "------getApplicationContext------" + getApplicationContext());
requestQueue = Volley.newRequestQueue(context);
}
} }
return requestQueue; } /**
* 将请求放入消息队列中,tag是每个请求在消息队列的标签,方便对其经行控制
*
* @param request
* @param tag
*/
public <T> void addToRequestQuere(Request<T> request, String tag)
{
request.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
VolleyLog.d("Adding request to queue: %s", request.getUrl());
getRequestQueue(context).add(request);
} /**
* 将请求放入消息队列中,tag是使用的是默认标签
*
* @param request
* @param tag
*/
public <T> void addToRequestQuere(Request<T> request)
{
request.setTag(TAG);
getRequestQueue(context).add(request);
LogUtils.i(TAG, "网络请求已发出"); } /**
* 通过tag取消网络请求对像
*
* @param tag
*/ public void canclePendingRequest(Object tag)
{
if (requestQueue != null)
{
requestQueue.cancelAll(tag);
LogUtils.i(TAG, "网络请求已取消");
}
}</span>
}</span>

里面的注释比较清楚,就不一一赘述了。在第一次进行网络请求时构建线程池,以后请求只是将Request对象放入线程池即可。不过这样是有风险的,如 果程序在运行中崩溃,后面就会连续崩溃,一直闪退到创建线程池的那个界面。不过也可以在每次网络请求时都创建一个消息队列,但是想想每进行网络请求都创建 一个线程池是多么奢侈,而且也会浪费不必要的资源。Volley中StringRequest其实是在项目中是用的比较多的,下面就是我使用 StringRequest示例:

     <span style="font-size:14px;"> /**
* 意见反馈接口
*/
private void userFeedbackTask()
{
StringRequest stringRequest = new StringRequest(Request.Method.POST(请求类型), feedback(网络请求地址), new Listener<String>()
{ @Override
public void onResponse(String response)
{
Gson gson = new Gson();
OutJsonArrayJson outJsonArrayJson = gson.fromJson(response, new TypeToken<OutJsonArrayJson>()
{
}.getType());
if (outJsonArrayJson.getCode() == 200)
{
// 退出该页面
AppManager.getAppManager().finishActivity(getCurActivity());
ToastManagerUtils.show("反馈成功", getCurActivity());
}
ToastManagerUtils.show(outJsonArrayJson.getMsg(), getCurActivity());
dialog.dismiss();
}
}, new ErrorListenerCallBack())
{
@Override
protected Map<String, String> getParams()
throws AuthFailureError
{
Map<String, String> map = new HashMap<String, String>();
map.put("uid",
SharedPreferencesUtils.GetUserLoginDatailsValue(getCurActivity(), "GatherLuckUserDetails", "uid")); map.put("pwd",
SharedPreferencesUtils.GetUserLoginDatailsValue(getCurActivity(), "GatherLuckUserDetails", "pwd")); map.put("content", edActivityFeedbackInput.getText().toString().trim());
LogUtils.i(TAG,"意见反馈接口参数---->"+map.toString());
return map;
}
};
VolleyController.getInstance().addToRequestQuere(stringRequest);
}</span>

这是我项目中的一个"意见反馈接口"例子,写的一般希望大家多提意见。下来再看看请求图片示例:

     <span style="font-size:14px;">/**
* 获得用户头像
*/
private void getNetWorkImage(final String url)
{
/**
* 使用ImageRequest加载网络图片
*/
ImageRequest imageRequest = new ImageRequest(url, new Listener<Bitmap>()
{ @Override
public void onResponse(Bitmap response)
{
rimgActivityDetailsOfMineHeadImage.setImageBitmap(response);
}
}, 60, 100, Config.ARGB_8888, new ErrorListenerCallBack());
VolleyController.getInstance().addToRequestQuere(imageRequest);
}</span>

这是我项目中获取用户头像的例子,将网络图片地址传入,返回Bitmap对象,这里 Bitmap默认32位ARGB位图,位图数越高,图片越逼真。60为Bitmap最大宽度,100为最大高度。以上就是Volley在项目中经常使用的 地方。不过比较悲催的一点是:Volley没有直接的文件上传请求,不过可以扩展的,网上有封装好的。

下来我就说一下xUtils的基本使用,其实说起Xutils它很不错,但我不太习惯,用起来总感觉碍手碍脚的。各种封装的都很好,包含DbUtils模块,ViewUtils模块,HttpUtils模块,BitmapUtils模块。

因为它封装的比较完善,我用的时候只是封装了BitmapUtils。上代码:

     <span style="font-size:14px;"> private void submitFeedbackTask()
{
try{ RequestParams requestParams = new RequestParams();
requestParams.addBodyParameter("act", "feedback");
requestParams.addBodyParameter("content", edActivityFeedbackInput.getText().toString().trim());
HttpUtils httpUtils = new HttpUtils();
httpUtils.send(HttpMethod.POST, QueryAddress.Feed_Back, requestParams, new RequestCallBack<String>()
{ @Override
public void onFailure(HttpException arg0, String arg1)
{
// TODO Auto-generated method stub
ToastManagerUtils.show("提交失败", getCurActivity());
dialog.cancel();
} @Override
public void onSuccess(ResponseInfo<String> arg0)
{
OutJsonArrayJson<String> outJsonArrayJson =
gson.fromJson(arg0.result, new TypeToken<OutJsonArrayJson<String>>()
{
}.getType());
if (outJsonArrayJson.getCode() == 200)
{
ToastManagerUtils.show("提交成功", getCurActivity());
AppManager.getAppManager().finishActivity(getCurActivity());
}
dialog.cancel();
} @Override
public void onLoading(long total, long current, boolean isUploading)
{
dialog.show();
}
});</span>
<span style="font-size:14px;">}catch(Ex e){
}
}</span>

这是我另一个项目的"意见反馈"网络请求,可以看出它已经将访问失败和成功封装。但是我一般在onFailure()里面做是否链接网络判断的。 下来再看看BitmapUtils的使用。

这里我简单封装了一下,其实也就是借鉴的网上的;

 public class xUtilsImageLoader
{
private BitmapUtils bitmapUtils; private Context mContext; private View view; // otherOrImage为true是设置view背景
private boolean otherOrImage; @SuppressWarnings("unused")
public xUtilsImageLoader(Context context)
{
// TODO Auto-generated constructor stub
this.mContext = context; bitmapUtils = new BitmapUtils(mContext);
bitmapUtils.configDefaultLoadingImage(R.drawable.bg_default_truth_words);// 正在加载时显示图片
bitmapUtils.configDefaultLoadFailedImage(R.drawable.bg_default_truth_words);// 加载失败时显示图片
bitmapUtils.configDefaultBitmapConfig(Bitmap.Config.RGB_565);// Bitmap的位图格式 } /**
*
* @author sunglasses
* @category 鍥剧墖鍥炶皟鍑芥暟
*/
public class CustomBitmapLoadCallBack extends DefaultBitmapLoadCallBack<ImageView>
{ @Override
public void onLoading(ImageView container, String uri, BitmapDisplayConfig config, long total, long current)
{
} @Override
public void onLoadCompleted(ImageView container, String uri, Bitmap bitmap, BitmapDisplayConfig config,
BitmapLoadFrom from)
{
fadeInDisplayNormal(container, view, bitmap, otherOrImage);
} @Override
public void onLoadFailed(ImageView container, String uri, Drawable drawable)
{
// TODO Auto-generated method stub }
} private static final ColorDrawable TRANSPARENT_DRAWABLE = new ColorDrawable(android.R.color.transparent); /**
* @author sunglasses
* @category 鍥剧墖鍔犺浇鏁堟灉
* @param imageView
* @param bitmap
*/ @SuppressLint("NewApi")
private void fadeInDisplayNormal(ImageView imageView, View view, Bitmap bitmap, boolean otherOrImage)
{
// 设置图片加载动画
final TransitionDrawable transitionDrawable =
new TransitionDrawable(new Drawable[] {TRANSPARENT_DRAWABLE,
new BitmapDrawable(imageView.getResources(), bitmap)});
if (otherOrImage)
{
view.setBackground(transitionDrawable);
}
else
{
imageView.setImageDrawable(transitionDrawable);
}
transitionDrawable.startTransition(300); } public void display(View view, String url, boolean otherOrImage)
{
bitmapUtils.display(new ImageView(mContext), url, new CustomBitmapLoadCallBack());
this.view = view;
this.otherOrImage = otherOrImage;
} public void clearCache()
{
bitmapUtils.clearMemoryCache();
} public void clearCache(String url)
{
bitmapUtils.clearCache(url);
} public void setFailedImage(int id)
{
bitmapUtils.configDefaultLoadFailedImage(id);
}
}

我发现有时候加载网络图片,有图片出不来的问题。而且它是有图片缓存的。让人真的很不爽。原生的BitmapUtils不能传入自定义View,比如常见 的RoundImageView等。我看同事的是写回调来获得Bitmap对象,我是直接将自定义View传入,通过otherOrImage这个 boolean判断的,有点偷奸耍滑的感觉。其实大家也可以看看Glide这个图片请求框架,很不错的。好了就到这吧,该下班了。其实都是些比较基础的, 这也是受到了工作年龄的限制。希望以后可以给大家带来些有用的。反正努力就是了。