我使用 API 登录,如果登录成功,它会返回代码 200 和响应。如果不正确的电子邮件或密码将返回代码 401,json 对象包含错误 问题是我想获得网络响应,即使请求代码不等于 200,如图像
但是 volley 抛出异常 BasicNetwork.performRequest: Unexpected response code 401
这是我的代码
public interface OnResponse{
void onResponse(JSONObject response) throws Exception;
void onErrorResponse(VolleyError volleyError);
}//OnResponse
public static void newRequest(Context context, String url, final Map<String, String>params, final OnResponse onResponse){
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
RequestQueue queue = Volley.newRequestQueue(context);
//
//onErrorResponse()
//onResponse()
StringRequest stringRequest = new StringRequest(Request.Method.POST, url, response -> {
// - - - - - - - - - - - - - - - - - - - - -
try {
JSONObject object = new JSONObject(response);
onResponse.onResponse(object);
} catch (Exception e) {
Log.e(TAG, "FLAG-1");
e.printStackTrace();
}
// - - - - - - - - - - - - - - - - - - - - -
}, error -> {
Log.e(TAG, "FLAG-2");
onResponse.onErrorResponse(error);
}){
@Override
protected VolleyError parseNetworkError(VolleyError volleyError) {
volleyError.printStackTrace();
Log.e("zxc", volleyError.getMessage()+"");
Log.e("zxc", volleyError.getLocalizedMessage()+"");
return super.parseNetworkError(volleyError);
}
};
//
stringRequest.setParams(params);
stringRequest.setShouldCache(false);
queue.add(stringRequest);
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
}//newRequest()`
最佳答案
VolleyError
具有 networkResponse
属性,它包含响应。
这是一个示例:String response = new String(error.networkResponse.data);
关于android - 如何获得网络响应,即使状态代码不是 200,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55180615/