我想从数据库中获取用户的信息并显示它,但我一直收到此错误:
BasicNetwork.performRequest:意外的响应代码404
这是我的javacode:
加载方法:
public void loadUserProfile() {
Response.Listener<String> responseListener = new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
idTV.setText(jsonResponse.getString("_id"));
nameTV.setText(jsonResponse.getString("name"));
firstNameTV.setText(jsonResponse.getString("firstName"));
emailTV.setText(jsonResponse.getString("email"));
sexTV.setText(jsonResponse.getString("sex"));
yearTV.setText(jsonResponse.getString("year"));
cursusTV.setText(jsonResponse.getString("cursus"));
} catch (JSONException e) {
onLoadProfileFail();
}
}
};
ProfileRequest profileRequest = new ProfileRequest(user_id, responseListener);
RequestQueue queue = Volley.newRequestQueue(ProfileActivity.this);
queue.add(profileRequest);
}
请求类
class ProfileRequest extends StringRequest {
private static final String USER_PROFILE_REQUEST = "http://[ipaddress]:8080/users/:id";
private Map<String, String> params;
public ProfileRequest(String id, Response.Listener<String> listener) {
super(Method.POST, USER_PROFILE_REQUEST, listener, null);
params = new HashMap<>();
params.put("id", id);
}
@Override
public Map<String, String> getParams() {
return params;
}
}
app.js
router.get('/users/:id', function(req, res) {
User.find({ _id: "ie00847" }, function(err, user) {
if (err)
res.send(err);
res.json(user);
});
});
答案 0 :(得分:0)
由于您使用不可用的方法(POST)访问路由,因此出现404错误,因为在app.js
文件中您为get请求而不是POST请求定义了一个函数,因此您需要将Android代码更新为GET请求。如下所示,
class ProfileRequest extends StringRequest {
private static final String USER_PROFILE_REQUEST = "http://[ipaddress]:8080/users";
private Map<String, String> params;
public ProfileRequest(String id, Response.Listener<String> listener) {
super(Method.GET, USER_PROFILE_REQUEST + "/" + id, listener, null);
}
}
另请注意,由于您不再发送POST请求,因此无需覆盖getParams()
方法。此外,除了通过对URL中的值进行硬编码而不是通过Map
对象进行硬编码之外,您无法向GET请求添加参数。
希望这会有所帮助:)
答案 1 :(得分:0)
您可以使用此代码来解决
public void onErrorResponse(VolleyError error) {
NetworkResponse response = error.networkResponse;
if (response != null && response.statusCode == 404) {
try {
String res = new String(response.data,
HttpHeaderParser.parseCharset(response.headers, "utf-8"));
// Now you can use any deserializer to make sense of data
JSONObject obj = new JSONObject(res);
//use this json as you want
} catch (UnsupportedEncodingException e1) {
// Couldn't properly decode data to string
e1.printStackTrace();
} catch (JSONException e2) {
// returned data is not JSONObject?
e2.printStackTrace();
}
}
}