com.android.volly.AuthFailureError in making basic volly POST request to a django server

前端 未结 2 639
遥遥无期
遥遥无期 2020-12-10 17:58

I am trying to connect to a django server from my android application. I am trying to access my api, making a POST request with volly. Everything is set. All th

相关标签:
2条回答
  • 2020-12-10 18:24

    i solved it my self... This code will get you an auth-token, with the username and password you provide, and then that token will be put in the header to get data from the server...

    public void vollyRequestGetAuthToken()
    {
        RequestQueue queue  = Volley.newRequestQueue(this);
        StringRequest request =  new StringRequest(Request.Method.POST  , "https://example.com/get-auth-token/", new Response.Listener<String>() {
    
            @Override
    
        public void onResponse(String response) {
            Toast.makeText(MainActivity.this, "RESPONSE: " + response, Toast.LENGTH_SHORT ).show();
            System.out.println("RESPONSE:          >>> " + response + "<<<");
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Toast.makeText(MainActivity.this, "ERROR: " + error, Toast.LENGTH_SHORT ).show();
        }
    }) {
        @Override
        protected Map<String,String> getParams(){
            Map<String,String> params = new HashMap<String, String>();
            params.put("username","*****");
            params.put("password","*****");
            return params;
        }
        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            Map<String,String> params = new HashMap<String, String>();
            params.put("Authorization",
                    String.format("Basic %s", Base64.encodeToString(
                            String.format("%s:%s", "<username>", "<password>").getBytes(), Base64.DEFAULT)));
            params.put("username" , "*****" );
            params.put("password" , "*****" );
            return params;
        }
    };
        queue.add(request);
    }
    

    and now when you have the auth-token, use the following code to send auth-token to get data

    @Override
                public Map<String, String> getHeaders() throws AuthFailureError {
                    HashMap<String, String> headers = new HashMap<String, String>();
                    headers.put("Authorization", "Token <token>");
                    return headers;
                }
    
    0 讨论(0)
  • 2020-12-10 18:41

    This is caused when the request is declined/blocked from the API End Point. The reason could be a malformed request for that,

    • Check your request type [GET/POST/ANY OTHER]
    • Check the request Header and Body
    0 讨论(0)
提交回复
热议问题