Search code examples
javaandroiddjangodjango-rest-frameworkandroid-volley

how to get volley cookies and set it on next request - android


I use Django, when the user logs in through the API, the response that is sent to Android contains a cookie that includes CSRF and session, and I need to receive its values and send them in the header in the next request. I tried a lot, but the way I did not find a solution

    private void test() {
        RequestQueue requestQueue;
        requestQueue = Volley.newRequestQueue(this);
        String url_ = "https://xxxx.com/api/BF";
        Map<String, String> params = new HashMap<>();
        params.put("Email", UEmail);
        params.put("Password", UPassword);
        JSONObject JOParams = new JSONObject(params);

        
        JsonObjectRequest JORequest = new JsonObjectRequest(Request.Method.POST, url_, JOParams, response -> {
            try {
                String status_ = response.getString("Status");
                if (status_.equals("OK_")) {
                    Toast.makeText(this, "Login", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(this, "Login failed", Toast.LENGTH_SHORT).show();
                }
            } catch (Exception e) {
                Toast.makeText(this, "Data error", Toast.LENGTH_SHORT).show();
            }
        }, error -> {
            Toast.makeText(this, "Connection failed", Toast.LENGTH_LONG).show();
        });
        requestQueue.add(JORequest);
    }

}

Please complete the code. I went through all the previous answers and didn't get any results


Solution

  • Use the code below.

        private void test() {
            RequestQueue requestQueue;
            requestQueue = Volley.newRequestQueue(this);
            String url_ = "https://xxxx.com/api/BF";
            Map<String, String> params = new HashMap<>();
            params.put("Email", UEmail);
            params.put("Password", UPassword);
            JSONObject JOParams = new JSONObject(params);
    
            
            JsonObjectRequest JORequest = new JsonObjectRequest(Request.Method.POST, url_, JOParams, response -> {
                try {
                    String status_ = response.getString("Status");
                    if (status_.equals("OK_")) {
                        Toast.makeText(this, "Login", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(this, "Login failed", Toast.LENGTH_SHORT).show();
                    }
                } catch (Exception e) {
                    Toast.makeText(this, "Data error", Toast.LENGTH_SHORT).show();
                }
            }, error -> {
                Toast.makeText(this, "Connection failed", Toast.LENGTH_LONG).show();
            }) {
                @Override
                public Map<String, String> getHeaders() {
                    Map<String, String>  params = new HashMap<>();
                    params.put("User-Agent", "BalesApp");
                    if(!csrftoken.isEmpty()){
                        String CookeVAL = "csrftoken=" + csrftoken + "; sessionid=" + sessionid + ";";
                        params.put("Cookie", CookeVAL);
                        params.put("X-CSRFToken", csrftoken);
                    }
    
    
                    return params;
                }
                @Override
                protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
                    int x;
                    AHeaders = response.allHeaders;
                    for (int n = 0; n< Objects.requireNonNull(AHeaders).size(); n++ ){
                        if(AHeaders.get(n).getName().equals("set-cookie")){
                            HeadVal = AHeaders.get(n).getValue();
                            x = HeadVal.indexOf("csrftoken=");
                            if(x >= 0){
                                int x1 = HeadVal.indexOf("=");
                                int x2 = HeadVal.indexOf(";");
                                csrftoken = HeadVal.substring(x1+1,x2);
                            }
    
                            x = HeadVal.indexOf("sessionid=");
                            if(x >= 0){
                                int x1 = HeadVal.indexOf("=");
                                int x2 = HeadVal.indexOf(";");
                                sessionid = HeadVal.substring(x1+1,x2);
                            }
                        }
                    }
    
                    return super.parseNetworkResponse(response);
                }
            };
            requestQueue.add(JORequest);
        }
    
    }