【发布时间】:2020-07-11 21:46:37
【问题描述】:
我的 Android 应用向 REST API 发送请求以验证用户身份。服务器对该请求返回 true。但是在我的应用程序中遇到onErrorResponse() 而没有遇到onResponse()。而我打印的错误:
com.android.volley.ParseError: org.json.JSONException: Value [{"id":1,"username":"vuthehuyht","full_name":"Vũ Thế Huy","phone_number":"0972809817","password":"hoanglan"}] of type org.json.JSONArray cannot be converted to JSONObject
验证用户功能
final RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("phone_number", phoneNumber);
jsonObject.put("password", password);
} catch (JSONException e) {
e.printStackTrace();
}
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, "http://192.168.53.100:3001/user/auth", jsonObject, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
loadingBar.dismiss();
Toast.makeText(LoginActivity.this, "Login successfully", Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
loadingBar.dismiss();
Toast.makeText(LoginActivity.this, "Error", Toast.LENGTH_SHORT).show();
System.out.println(error.toString());
}
});
requestQueue.add(jsonObjectRequest);
user.controller.js
exports.auth = (req, res) => {
const phone_number = req.body.phone_number;
const password = req.body.password;
User.findAll({
where: {
phone_number: phone_number,
password: password
}
})
.then(data => {
res.send(data);
res.end();
})
.catch(err => {
res.status(500).send({
message: err.message | "Could not found user!"
});
res.end();
})
};
我该如何解决?
【问题讨论】:
-
您的服务器是您将请求发送到的服务器吗?如果是这样,请将响应的格式更改为其中包含 JSONArray 的 JSONObject。
-
Volley 中还有一个
JsonArrayRequest,所以也许应该使用它而不是JsonObjectRequest,因为您显然收到了一个 JSON 数组。 -
在请求中有
phone_number和password字段。使用JsonArrayRequest或JsonObjectRequest?