Android Rest身份验证未返回状态代码或网络响应

时间:2019-04-15 19:39:59

标签: android django django-rest-framework jwt android-volley

我有一个使用django REST API后端的Android,该后端包括基于令牌的身份验证。 问题在于,每当用户提供错误的电子邮件或密码时,我都会从下面的代码中看到403错误,但是截击库没有得到响应代码。

这是Django rest中的支持服务。

def api_authenticate_user(request):
    try:
        email = request.data['email']
        password = request.data['password']
        user = authenticate(email=email, password=password)
        if user is not None:
            try:
                payload = jwt_payload_handler(user)
                token = jwt.encode(payload, settings.SECRET_KEY)
                user_logged_in.send(sender=user.__class__, request=request, user=user)
                user = User.objects.get(email=email)
                user_details = {'token': token, 'names': user.get_name(), 'id': user.id}
                return JsonResponse(user_details, status=status.HTTP_200_OK)
            except Exception as e:
                raise e
        else:
            return JsonResponse({'error': 'Invalid email address or password', 'status': status.HTTP_403_FORBIDDEN})
    except KeyError:
        return JsonResponse({'error': 'Provide email and password', 'status': status.HTTP_403_FORBIDDEN})

在我的android应用中,这就是尝试获取响应代码的方式,以便我可以提醒用户输入正确的凭据。

private void UserLoginTask(final String email, final String password) {
    StringRequest request = new StringRequest(Request.Method.POST, loginUrl , new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            try {
                JSONObject userObj = new JSONObject(response);
                userSession.initializeSession(userObj.getString("names"), email, userObj.getString("token"));
                Intent intent = new Intent(Login.this, MainActivity.class);
                startActivity(intent);
                finish();
            } catch (JSONException e) {
                e.printStackTrace();
                errorText.setText("Could not process your request. Try again");
                errorText.setVisibility(View.VISIBLE);
                showProgress(false);
            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            System.out.println(error.networkResponse);
            if(error.networkResponse.statusCode == 403){
                errorText.setText("Invalid email address or password");
            }else{
                errorText.setText("Could not process your request. Try again");
            }
            errorText.setVisibility(View.VISIBLE);
            showProgress(false);
        }
    }){
        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
            Map<String, String> params = new HashMap<>();
            params.put("email", email);
            params.put("password", password);
            return params;
        }
    };

    RequestQueue queue = Volley.newRequestQueue(Login.this);
    queue.add(request);

}

当我尝试记录或获取齐射错误侦听器类中显示的错误状态时,出现此错误,表明响应网络状态为null。如何获取403或其他任何状态代码。

2019-04-15 22:24:46.461 31397-31397/com.example.phanue.antenatal E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.phanue.antenatal, PID: 31397
    java.lang.NullPointerException: Attempt to read from field 'int com.android.volley.NetworkResponse.statusCode' on a null object reference
        at com.example.phanue.antenatal.LoginData.Login$4.onErrorResponse(Login.java:153)
        at com.android.volley.Request.deliverError(Request.java:564)
        at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:101)
        at android.os.Handler.handleCallback(Handler.java:789)
        at android.os.Handler.dispatchMessage(Handler.java:98)
        at android.os.Looper.loop(Looper.java:164)
        at android.app.ActivityThread.main(ActivityThread.java:6942)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)

1 个答案:

答案 0 :(得分:1)

检查空指针以避免NullPointerException

 @Override
    public void onErrorResponse(VolleyError error) {
        if (error != null && error.networkResponse != null && error.networkResponse.statusCode == 403) {
        errorText.setText("Invalid email address or password");
}
    else{errorText.setText("Could not process your request. Try again");
}