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

前端 未结 2 645
遥遥无期
遥遥无期 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() {
    
            @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 getParams(){
            Map params = new HashMap();
            params.put("username","*****");
            params.put("password","*****");
            return params;
        }
        @Override
        public Map getHeaders() throws AuthFailureError {
            Map params = new HashMap();
            params.put("Authorization",
                    String.format("Basic %s", Base64.encodeToString(
                            String.format("%s:%s", "", "").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 getHeaders() throws AuthFailureError {
                    HashMap headers = new HashMap();
                    headers.put("Authorization", "Token ");
                    return headers;
                }
    

提交回复
热议问题