1.添加依赖
compile ‘com.mcxiaoke.volley:library:1.0.19’已弃用,现在用
compile ‘com.android.volley:volley:1.0.0’
2.copy文件夹http_volley
3.在application里
public static final String TAG = CGBapplication.class.getSimpleName();
private RequestQueue mRequestQueue;
private ImageLoader mImageLoader;
...
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(getApplicationContext());
}
return mRequestQueue;
}
public ImageLoader getImageLoader() {
getRequestQueue();
if (mImageLoader == null) {
mImageLoader = new ImageLoader(this.mRequestQueue,
new LruBitmapCache());
}
return this.mImageLoader;
}
public <T> void addToRequestQueue(Request<T> req, String tag) {
// set the default tag if tag is empty
req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
getRequestQueue().add(req);
}
public <T> void addToRequestQueue(Request<T> req) {
req.setTag(TAG);
getRequestQueue().add(req);
}
public void cancelPendingRequests(Object tag) {
if (mRequestQueue != null) {
mRequestQueue.cancelAll(tag);
}
}
4.在BaseActivity或BaseFragment中
//*************与服务器交互封装start************//
public void loadData(String reqTag, RequestInfo reqInfo, boolean isShowDialog,
boolean cancelable, VolleyResponse.strReqCallback callback){
if (DeviceUtils.isHasNetWork()) {
// reqInfo.getBodyParams().put(); //添加公共参数
VolleyLoader.start(mContext).post(reqTag, reqInfo, isShowDialog, cancelable, callback);
} else {
showToast("请检查网络连接");
}
}
public void showToast(String content) {
Toast.makeText(mContext, content, Toast.LENGTH_SHORT).show();
}
5.在程序中用的时候
RequestInfo requestInfo = new RequestInfo(URLS.LOGIN);
requestInfo.addBodyParams("username", "13203811868");
requestInfo.addBodyParams("password","a123456");
requestInfo.addBodyParams("grant_type","password");
requestInfo.addBodyParams("client_secret","123@abc");
requestInfo.addBodyParams("client_id","consoleApp");
loadData(VolleyTag, requestInfo, true, true, new VolleyResponse.strReqCallback() {
@Override
public void success(String response) {
LoginModel login = JSON.parseObject(response, LoginModel.class);
if(login.getError()==null||login.getError().isEmpty()){
Intent toMain = new Intent(mContext, MainActivity.class);
startActivity(toMain);
finish();
}else{
showToast(login.getError_description());
}
}
@Override
public void error(VolleyError error) {
}
});