【发布时间】:2018-10-09 01:40:17
【问题描述】:
我正在使用 volley 在 android 中调用 http 请求,但有时我在收到响应时收到 JSON 解析错误,即使响应始终相同。
void login() throws JSONException {
RequestQueue queue = Volley.newRequestQueue(this);
String url = String.format("%s/login", getString(R.string.url));
JSONObject data = new JSONObject();
data.put("email", etEmail.getText().toString());
data.put("password", etPassword.getText().toString());
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
(Request.Method.POST, url, data, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Helper.unblockUI(pb, getWindow());
try{
if(response.has("error")){
Toast.makeText(LoginActivity.this, response.getString("error"), Toast.LENGTH_SHORT).show();
}else if(response.has("id") && response.has("token")){
enterMainActivity();
}else{
Toast.makeText(LoginActivity.this, "Something is wrong", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e){
Helper.unblockUI(pb, getWindow());
Toast.makeText(LoginActivity.this, e.toString(), Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Helper.unblockUI(pb, getWindow());
Toast.makeText(LoginActivity.this, error.toString(), Toast.LENGTH_SHORT).show();
}
});
Helper.blockUI(pb, getWindow());
queue.add(jsonObjectRequest);
}
响应是:
{"error":"Email doesn't exist"}
当响应是这样时它不会出错,因为那是有效的 JSON, 我不知道为什么,但有时响应是这样的:
{"error":"Email doesn't exist"
最后减去一个大括号,所以凌空响应是错误的,因为那不是有效的 JSON。
知道为什么会这样吗?因为有时它得到了有效的 json 有时没有,所以我总是从 api 返回相同的响应,但有时响应在 json 对象的末尾减去一个大括号..
成功时输出:
2018-10-09 21:05:22.717 12545-12545/com.omg_indo.itmsapp D/tag: {"error":"Email doesn't exist"}
出错时的输出:
2018-10-09 21:08:02.019 12545-12545/com.omg_indo.itmsapp D/tag: com.android.volley.ParseError: org.json.JSONException: Unterminated object at character 30 of {"error":"Email doesn't exist"
【问题讨论】:
标签: java android json android-volley