安卓网络请求连接框架Volley的使用之StringRequest请求和解析
发送StringRequest请求:以登录为例
String url = Const.SERVICE + "anUser/login.do";
try {
Thread.sleep(1000);
StringRequest stringRequest = new StringRequest(
Request.Method.POST, url, new Listener<String>() {
@Override
public void onResponse(String response) {
System.out.println("Response:"+ response.toString());
//接收结果解析
checkLogin(response.toString());
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
//自定义Dialog
showDialog1("网络连接异常");
System.out.println("Error:" + error.toString());
}
}) {
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("userTel", name);
params.put("passWord", pwd);
return params;
}
};
requestQueue.add(stringRequest);
} catch (InterruptedException e) {
e.printStackTrace();
}
上述已经从服务器端返回结果,自定义方法进行解析JSON
public void checkLogin(String result) {
if (result.equals(NOUSER)) {
accountNumber.setText("");
showDialog1("用户名不存在");
} else if (result.equals(PWDERROR)) {
password.setText("");
showDialog1("密码错误");
} else {
//添加application
application.setUserTel(accountNumber.getText().toString());
final MyDialog pd = MyProgressDialog.showProgressDialog(LoginActivity.this);
pd.show();
final Timer t = new Timer();
t.schedule(new TimerTask() {
public void run() {
pd.dismiss();
t.cancel();
}
}, 3000);
startActivity(new Intent(LoginActivity.this, MainActivity.class));
overridePendingTransition(R.anim.anim_in, R.anim.anim_out);
}
}