How to access a password protected URL in android using volley library

Viewed 159

I am trying to do the following task:

enter image description here

enter image description here

I am planning to use JsonObjectRequest (Volley Library) in my code and extract the credentials but I am not able to understand where would the Username and Password be required in the request. This is a code snippet. If anyone can tell where I need to authenticate the Username and Password in this code snippet to fetch the JSON Object, it would be very helpful.

JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(url, null, new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
                VolleyLog.wtf(response.toString());

        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            VolleyLog.wtf(error.getMessage(), "utf-8");
        }
    });

queue.add(jsonObjectRequest)
3 Answers

Create a jsonObject with username and password then pass this object to the JsonObjectRequest

Your code will be like this :

        JSONObject body= new JSONObject();

            body.put("username", "user");
            body.put("password", "userPassword");

            JsonObjectRequest jsonObjectRequest= new JsonObjectRequest(Request.Method.POST, url, 
              body, new Response.Listener<JSONObject>() {
             @Override
        public void onResponse(JSONObject response) {
                VolleyLog.wtf(response.toString());

        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            VolleyLog.wtf(error.getMessage(), "utf-8");
        }
    });

queue.add(jsonObjectRequest)

This is how you can use POST Method in volley:

StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
            @Override
            public void onResponse(final String response) {
                try {
                    JSONObject object = new JSONObject(response);
//                    here is your json object
                } catch (JSONException e) {
                    e.printStackTrace();
                }


            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
//                volley errors
            }
        }) {
            @Override
            protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<>();
                params.put("username", username);
                params.put("password", password);
                return params;
            }
        };

    queue.add(stringRequest);

You need to understand what is form-data and how it is used:

Definition and Usage

The method attribute specifies how to send form-data (the form-data is sent to the page specified in the action attribute).

The form-data can be sent as URL variables (with method="get") or as HTTP post transaction (with method="post").

Notes on GET:

  • Appends form-data into the URL in name/value pairs
  • The length of a URL is limited (about 3000 characters)
  • Never use GET to send sensitive data! (will be visible in the URL)
  • Useful for form submissions where a user wants to bookmark the result
  • GET is better for non-secure data, like query strings in Google

Notes on POST:

  • Appends form-data inside the body of the HTTP request (data is not shown in URL)
  • Has no size limitations

To pass username and password arguments as form-data you can create StringRequest and override it's getParams method to return a map of data.

StringRequest request = new StringRequest(
    Request.Method.POST,
    requestUrl,
    onResultListener,
    onErrorListener) {
        @Override
        protected Map<String, String> getParams() {
            HashMap<String, String> hashMap = new HashMap<>();
            hashMap.put("username", username)
            hashMap.put("password", password)
            return hashMap;
        }

        @Override
        protected Response<String> parseNetworkResponse(NetworkResponse response) {
            // You can parse response here and throw exceptions when required.
            return super.parseNetworkResponse(response);
        }
    };
queue.add(request)        
Related