我在Android Studio中有一个Stringrequest
并且它正常工作,我的意思是我得到了onResponse
方法的响应,现在我希望凌空在错误键具有真值时返回错误。我怎么能这样做?
这是我的要求:
StringRequest stringRequest = new StringRequest(Request.Method.POST, METHOD_ACCOUNT_OTP_REQUEST,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.i("response", response);
try {
JSONObject jsonObject = new JSONObject(response);
startVerificationActivity(jsonObject.get("sender").toString());
} catch (JSONException e) {
e.printStackTrace();
Log.i("error", e.toString());
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
}){
@Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("mobilePhoneNumber", phoneNumber);
params.put("clientId", CLIENT_ID);
return params;
};
这是服务器的答案:
{"sender":"10008727","error":true}
我想要的是在json中onErrorResponse
为error
时设置齐射以运行true
。
答案 0 :(得分:1)
您可以创建一个新的自定义AppStringRequest
类,该类继承自StringRequest
并处理上述用例。
public class AppStringRequest extends StringRequest {
// ... constructor ...
@Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
// You will receive your response here in the response parameter.
// parse the response and check whether the response has "error":true
String parsed;
try {
parsed = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
} catch (UnsupportedEncodingException e) {
parsed = new String(response.data);
}
// if it's an error, return Response.error(), otherwise, return Response.success()
try {
JSONObject resObj = new JSONObject(parsed);
boolean error = resObj.getBoolean("error");
if (error) {
return Response.error(new VolleyError());
} else {
return Response.success(parsed, HttpHeaderParser.parseCacheHeaders(response));
}
} catch (JSONException e) {
e.printStractTrace()
// your server response has some issues
}
return Response.error(new VolleyError("Error message")); // can send error message in the VolleyError
}
}
然后您必须使用此AppStringRequest
而不是默认StringRequest
。
StringRequest stringRequest = new AppStringRequest(Request.Method.POST, METHOD_ACCOUNT_OTP_REQUEST,
... )
错误讯息将在onErrorResponse
:
@Override
public void onErrorResponse(VolleyError error) {
Log.i("Volley error", error.toString()); //the error message
}