代码如下:
public void loginPost(String url, String emailAddress, String password){
Map<String, String> params = new HashMap();
params.put("email", emailAddress);
params.put("password", password);
JSONObject parameters = new JSONObject(params);
String LOGIN_REQUEST_TAG = "LOGIN_REQUEST_TAG";
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url, parameters, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.d("Login Response:", response.toString());
JSONObject responseOject = response;
if(responseOject.has("data")){
try {
Log.d("Data Response", responseOject.getString("data"));
} catch (JSONException e) {
e.printStackTrace();
}
}else if(responseOject.has("error")){
try {
errorMessage = responseOject.getString("error");
new AlertDialog.Builder(MainActivity.this)
.setTitle("Error")
.setMessage(errorMessage)
.setNegativeButton("OK", null)
.show();
} catch (JSONException e) {
e.printStackTrace();
}
}else{
//Server error. Come back again later
Log.d("Server error", "Server Error");
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
VolleyLog.e("Error at login: ", error.getMessage());
}
});
AppSingleton.getInstance(getApplicationContext()).addToRequestQueue(jsonObjectRequest,LOGIN_REQUEST_TAG);
}
所有参数和URL都是正确的,因为我在调试期间已对其进行了检查。而且在Postman中一切正常。但是,上面的代码不会进入onResponse
方法,并且我没有收到任何错误。但是它警告"responseOject"
是多余的。我做错了吗? Android开发的新手。
错误:
BasicNetwork.performRequest: Unexpected response code 401
这是一个POST API,我正在使用Request.Method.Post,为什么会收到该错误?
答案 0 :(得分:1)
在使用API之前,请先在Postman中对其进行测试。您将清楚了解正在发生的事情。 错误代码401表示您的参数错误。否则,您无权访问该API。
尝试使用此代码进行此类呼叫。
private void callNetwork(final String email, final String password) {
String json_object_request = "jsonObjectRequest";
//Creating a string request
StringRequest stringRequest = new StringRequest(Request.Method.POST, Config.URL_LOGIN,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
if (response != null) {
parseData(response);
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
progressBar.setVisibility(View.GONE);
}
}) {
@Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
//Adding parameters to request
params.put("email", email);
params.put("password", password);
//returning parameter
return params;
}
};
//Adding the string request to the queue
AppController.getInstance().addToRequestQueue(stringRequest, json_object_request);
}