说到Volley,则需要了解Volley这个框架,这里我就不用多说了,博客有转载。。。。
这里我就直接上代码了:
并且有注释:
import java.net.URLDecoder; import android.app.Dialog; import android.content.DialogInterface; import android.util.Log; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.TypeReference; import com.android.volley.NetworkResponse; import com.android.volley.Request; 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.HttpHeaderParser; import com.microidea.util.Algorithm;
这个框架封装了request 需要继承它,自己写一个BaseRes<Data> 一定要继承request public abstract class BaseRequest<Params, Data> extends Request<BaseRes<Data>> implements DialogInterface.OnCancelListener { private static final String SERVER = "http://http://blog.csdn.net/lggisking";//服务器接口地址 private static final String KEY = "VOLLEY";//你应用的APP密钥 private final Params mParams; private final Dialog mDialog; private final Listener<BaseRes<Data>> mListener; private final ErrorListener mErrorListener; public BaseRequest(int method, String url, Params params, Listener<BaseRes<Data>> listener, ErrorListener errorlistener) { this(method, url, params, listener, errorlistener, null); } public BaseRequest(int method, String url, Params params, Listener<BaseRes<Data>> listener, ErrorListener errorlistener, Dialog dialog) { super(method, getReqUrl(url, params), null); mParams = params; mDialog = dialog; mListener = listener; mErrorListener = errorlistener; if (mDialog != null) { mDialog.setOnCancelListener(this); } } private static String getReqUrl(String m, Object p) { try { String Params = Algorithm.DesEncrypt(JSON.toJSONString(p), KEY); String Sign = Algorithm.Md5Encrypt(KEY + "Method" + m + "Params" + Params + KEY); return SERVER + "?" + "Method=" + m + "&Params=" + Params + "&Sign=" + Sign; } catch (Exception e) { return null; } } @Override public void onCancel(DialogInterface dialog) { cancel(); } @Override public Request<?> setRequestQueue(RequestQueue requestQueue) { if (mDialog != null && !mDialog.isShowing()) { mDialog.show(); } return super.setRequestQueue(requestQueue); } @Override protected Response<BaseRes<Data>> parseNetworkResponse( NetworkResponse response) { String data = new String(response.data); Log.d("Request", "==================== ADDR ====================\n" + getUrl()); Log.d("Request", "==================== PARAMS ====================\n" + JSON.toJSONString(mParams)); try { BaseRes<Data> result = JSON.parseObject(data, getType()); //FastJson框架 Log.d("Request", "==================== RESULT ====================\n" + data); if (result.verification) { return Response.success(result, HttpHeaderParser.parseCacheHeaders(response)); } else { return Response.error(new AsError(result.error)); } } catch (Exception e) { Log.d("Request", "==================== RESULT ====================\n" + data); Log.e("Request", "==================== ERRORS ====================", e); return Response.error(new DecryptError(e)); } } @Override protected void deliverResponse(BaseRes<Data> response) { if (mListener != null && !isCanceled()) { mListener.onResponse(response); } if (mDialog != null && mDialog.isShowing()) { mDialog.cancel(); } } @Override public void deliverError(VolleyError error) { if (!(error instanceof DecryptError) && !(error instanceof AsError) && !isCanceled()) { Log.d("Request", "==================== ADDR ====================\n" + getUrl()); Log.d("Request", "==================== PARAMS ====================\n" + JSON.toJSONString(mParams)); Log.e("Request", "==================== ERRORS ====================", error); } if (mErrorListener != null && !isCanceled()) { mErrorListener.onErrorResponse(error); } if (mDialog != null && mDialog.isShowing()) { mDialog.cancel(); } } protected abstract TypeReference<BaseRes<Data>> getType();//通过请求来的JSON数据进行解析绑定到实体类 }
这个类的作用:一个泛型基类,每个请求类继承它,请求实体类传入相应的字段:
public class BaseRes<Data> { public boolean verification; public ArrayList<Data> data; }
整个请求,绑定,,都在这一个类中完成
public class ReqPhoneCode extends BaseRequest<ReqPhoneCode.Params, ReqPhoneCode.Data> { / public ReqPhoneCode(Params params, Listener<BaseRes<Data>> listener, ErrorListener errorlistener) { super(Method.GET, "action", params, listener, errorlistener); } public ReqPhoneCode(Params params, Listener<BaseRes<Data>> listener, ErrorListener errorlistener, Dialog dialog) { super(Method.GET, "action", params, listener, errorlistener, dialog); }
//request的参数实体类 public static class Params { public String mobile; public String type; public Params(String mobile, String type) { super(); this.mobile = mobile; this.type = type; } } //response实体类 public static class Data { public String code; public String msg; public String total; } @Override protected TypeReference<BaseRes<Data>> getType() { return new TypeReference<BaseRes<Data>>() {
}; } }
接下来就是在Activity如何去用Volley框架了,,上面已经做好了整个流程,接下来会非常的简单
很奇怪Response需要手动导入包:import com.android.volley.Response;
public class ActivityCode extends Activity implements OnClickListener, Response.Listener<BaseRes<ReqPhoneCode.Data>>, Response.ErrorListener { private Button bt_code; private EditText et_code; private RequestQueue queue; private Params paramCode; private ReqPhoneCode requestcode; private String mobileNum; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_code); bt_code = (Button) findViewById(R.id.bt_code); et_code = (EditText) findViewById(R.id.recode); bt_code.setOnClickListener(this); queue = Volley.newRequestQueue(this); //得到Voley对象 } @Override public void onClick(View v) { requestCode(); } private void requestCode() { mobileNum = et_code.getText().toString().trim(); if (mobileNum.length() > 1) { paramCode = new ReqPhoneCode.Params(mobileNum, ""); requestcode = new ReqPhoneCode(paramCode, this, this); queue.add(requestcode);//把整个请求加入到queue中 会得到两个方法<span style="font-family: Arial, Helvetica, sans-serif;">onErrorResponse()</span><span style="font-family: Arial, Helvetica, sans-serif;">onResponse()分别是请求错误 和 请求成功 :可在这两个方法中完成相应的处理</span><span style="font-family: Arial, Helvetica, sans-serif;"> </span> } else { App.getInstance().Toast("请输入正确的手机号码"); } } @Override public void onErrorResponse(VolleyError error) { App.getInstance().showError(error); } @Override public void onResponse(BaseRes<Data> response) { if (response.verification && response.total == 1) { Intent intent = new Intent(ActivityCode.this, ActivityRegist.class); intent.putExtra("code", response.data.get(0).code); intent.putExtra("number", mobileNum); startActivity(intent); finish(); } else if (response.verification && response.total == 0) { App.getInstance().Toast("获取验证码失败"); } } }
希望这篇文章对大家有用,还有什么什么有疑问的,可以留言....
版权声明:本文为博主原创文章,未经博主允许不得转载。
时间: 2024-09-29 14:13:54