Volley 网络请求工具类
将Volley 访问网络中的共性提取出来供其他方调用
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import android.content.Context;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request.Method;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ClearCacheRequest;
import com.android.volley.toolbox.DiskBasedCache;
import com.android.volley.toolbox.HttpHeaderParser;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.yuu.upost_b.util.DialogLoadingUtil;
public class SendHttp {
public static String JSESSIONID = null;
//RequestQueue任务队列设置成static,让所有请求都共用一个请求队列,避免volley的请求过多、线程没有关闭而OOM异常
public static RequestQueue mRequestQueue;
//SendHttp设置成单例模式
private static SendHttp instance = null;
private SendHttp() {}
public static SendHttp getInstance() {
if (instance==null) {
instance = new SendHttp();
}
return instance;
}
/** * 获取RequestQueue任务队列 * @param context * @return */
private static RequestQueue getRequestQueue(Context context) {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(context.getApplicationContext());
}
File cacheDir = new File(context.getCacheDir(), "/volley");
DiskBasedCache cache = new DiskBasedCache(cacheDir);
mRequestQueue.start();
// clear all volley caches.
mRequestQueue.add(new ClearCacheRequest(cache, null));
return mRequestQueue;
}
/** * * @param context * @param url * @param listener 网络连接成功事件 */
public static void SendHttpPost(final Context context,String url,final Listener<String> listener) {
//RequestQueue任务队列
RequestQueue mQueue = getRequestQueue(context);
//网络连接失败事件
ErrorListener errorListener = new ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(context, "网络响应失败!", Toast.LENGTH_SHORT).show();
//只要执行到此处,就需要隐藏加载等待动画
DialogLoadingUtil.dismissLoadingDialog();
}
};
//网络字符串请求
StringRequest stringRequest = new StringRequest(Method.POST, url, listener, errorListener);
//队列中加入请求
mQueue.add(stringRequest);
}
/** * * @param context * @param url * @param listener 网络连接成功事件 * @param paramsMap 键值对参数 */
public static void SendHttpPost(final Context context,String url,final Listener<String> listener,final Map<String, String> paramsMap) {
//RequestQueue任务队列
RequestQueue mQueue = getRequestQueue(context);
//网络连接失败事件
ErrorListener errorListener = new ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(context, "网络响应失败!", Toast.LENGTH_SHORT).show();
//只要执行到此处,就需要隐藏加载等待动画
DialogLoadingUtil.dismissLoadingDialog();
}
};
//网络字符串请求
StringRequest stringRequest = new StringRequest(Method.POST, url, listener, errorListener){
//放入键值对参数
@Override
protected Map<String, String> getParams() throws AuthFailureError {
// TODO Auto-generated method stub
return paramsMap;
}
};
//队列中加入请求
mQueue.add(stringRequest);
}
/** * 需要自己定义请求失败监听器时的网络请求 * @param context * @param url * @param listener 网络请求成功 * @param errorListener 网络请求失败 * @param paramsMap 键值对参数 */
public static void SendHttpPost(final Context context,String url,final Listener<String> listener,
final ErrorListener errorListener,final Map<String, String> paramsMap) {
//RequestQueue任务队列
RequestQueue mQueue = getRequestQueue(context);
//网络字符串请求
StringRequest stringRequest = new StringRequest(Method.POST, url, listener, errorListener){
//放入键值对参数
@Override
protected Map<String, String> getParams() throws AuthFailureError {
// TODO Auto-generated method stub
return paramsMap;
}
};
//队列中加入请求
mQueue.add(stringRequest);
}
/** * * @param context * @param url * @param listener 网络连接成功事件 * @param paramsMap 键值对参数 * @param paramsHeaders 请求头参数 */
public static void SendHttpPost(final Context context,String url,final Listener<String> listener,final Map<String, String> paramsMap,final Map<String, String> paramsHeaders) {
//RequestQueue任务队列
RequestQueue mQueue = getRequestQueue(context);
//网络连接失败事件
ErrorListener errorListener = new ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(context, "网络响应失败!", Toast.LENGTH_SHORT).show();
//只要执行到此处,就需要隐藏加载等待动画
DialogLoadingUtil.dismissLoadingDialog();
}
};
//网络字符串请求
StringRequest stringRequest = new StringRequest(Method.POST, url, listener, errorListener){
//放入键值对参数
@Override
protected Map<String, String> getParams() throws AuthFailureError {
// TODO Auto-generated method stub
return paramsMap;
}
//设置请求头参数
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
// TODO Auto-generated method stub
return paramsHeaders;
}
};
//队列中加入请求
mQueue.add(stringRequest);
}
/** * 用于获取会话ID的方法,以保持会话 * 一般用于获取验证码后的操作 * 此方法获取的会话ID赋值给SESSIONID,以用作下一次网络请求的请求头参数 * @param context * @param url * @param listener 反映成功事件 * @param maps 键值对参数 */
public static void SendSMSCaptcha(final Context context,String url,Listener<String> listener,
final Map<String, String> maps,final ErrorListener errorListener) {
// TODO Auto-generated method stub
RequestQueue mQueue = getRequestQueue(context);
StringRequest stringRequest = new StringRequest(Method.POST, url, listener, errorListener ){
@Override
protected Map<String, String> getParams() throws AuthFailureError {
// TODO Auto-generated method stub
return maps;
}
@Override
protected Response<String> parseNetworkResponse(
NetworkResponse response) {
try {
Map<String,String> responseHeaders = response.headers;
JSESSIONID = responseHeaders.get("Set-Cookie");
String dataString = new String(response.data,"UTF-8");
return Response.success(dataString, HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
}
}
};
mQueue.add(stringRequest);
}
/** * 上传图片/文件 * @param url * @param avatarPath 图像路径 * @param paramFile */
public static void SendHttpPost(final Context context,String url,String avatarPath,String paramFile,
Listener<String> listener,final Map<String, String> maps){
RequestQueue mSingleQueue = getRequestQueue(context);
File file = new File(avatarPath);
if(!file.exists()){
Toast.makeText(context, "文件不存在", Toast.LENGTH_SHORT).show();
return;
}
ErrorListener errorListener = new ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(context, "网络响应失败!", Toast.LENGTH_SHORT).show();
//只要执行到此处,就需要隐藏加载等待动画
DialogLoadingUtil.dismissLoadingDialog();
}
};
List<File> list = new ArrayList<File>();
list.add(file);
MultipartRequest request = new MultipartRequest(url, listener
, errorListener, paramFile, file, maps);
mSingleQueue.add(request);
}
}
MainActivity中注册登录代码
public class MainActivity extends Activity {
EditText editText_phone;//电话号码
EditText editText_verificationCode;//验证码
EditText editText_password;//密码
Button button_login;//登录
Button button_regist;//注册
Button button_sendSMSCaptcha;//验证码
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView(); //初始化控件
//获取验证码
button_sendSMSCaptcha.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
String strPhone = editText_phone.getText().toString();
Map<String, String> paramsMap = new HashMap<String, String>();
paramsMap.put("phones", strPhone);
Listener<String> listener = new Listener<String>() {
@Override
public void onResponse(String result) {
// TODO Auto-generated method stub
Toast.makeText(MainActivity.this, "消息发送成功,请等待验证码:"+SendHttp.SESSIONID, Toast.LENGTH_SHORT).show();
Log.i("tag", "获取验证码result"+result);
Log.i("tag", "SESSIONID="+SendHttp.SESSIONID);
}
};
SendHttp.SendHttpPost__sendSMSCaptcha(MainActivity.this, HttpURL.sendSMSCaptcha_URL, listener, paramsMap);
}
});
//注册
button_regist.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
String strPhone = editText_phone.getText().toString();
String strVerificationCode = editText_verificationCode.getText().toString();
String strPassword = editText_password.getText().toString();
Map<String, String> maps = new HashMap<String, String>();
maps.put("mobile", strPhone);
maps.put("captcha", strVerificationCode);
maps.put("passwd", strPassword);
maps.put("repasswd", strPassword);
maps.put("type", "0");
Map<String, String> mapHeader = new HashMap<String, String>();
mapHeader.put("Cookie", SendHttp.SESSIONID);//请求头参数
Listener<String> listener = new Listener<String>() {
@Override
public void onResponse(String result) {
// TODO Auto-generated method stub
Toast.makeText(MainActivity.this, "注册result"+result, Toast.LENGTH_SHORT).show();
Log.i("tag", "注册result"+result);
}
};
SendHttp.SendHttpPost(MainActivity.this, HttpURL.register_URL, listener, maps, mapHeader);
}
});
//登录
button_login.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
String strPhone = editText_phone.getText().toString();
String strPassword = editText_password.getText().toString();
Map<String, String> maps = new HashMap<String, String>();
maps.put("mobile", strPhone);
maps.put("passwd", strPassword);
Listener<String> listener = new Listener<String>() {
@Override
public void onResponse(String result) {
// TODO Auto-generated method stub
Toast.makeText(MainActivity.this, "登录result"+result, Toast.LENGTH_SHORT).show();
Log.i("tag", "登录result"+result);
}
};
SendHttp.SendHttpPost(MainActivity.this, HttpURL.login_URL, listener, maps);
}
});