1

I am using Volley library in order to integrate my SettingsActivity with the server on Android Studio. I'm performing a request of GET method in order to retrieve the values from the server. But as i try to do the same, i get a volley error stating 401 Error.

I tested my url on POSTMAN application too. It showed the same 401 authorization error.

Question 1 : What are the reasons of getting such an error in Volley library for Android platform?

Question 2 : How can it be resolved so that the Volley requests can be performed on Android platform.

Code for Reference :

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setupActionBar();

        sharedPreferences = getSharedPreferences(getString(R.string.preference_file_key), Context.MODE_PRIVATE);
        final String userid=sharedPreferences.getString(getString(R.string.saved_user_id),"");
        Toast.makeText(this, userid, Toast.LENGTH_LONG).show();
        //final String userid=NetworkHelper.get().getUserIdFromSharedPreferences();

        //sharedPreferences=getSharedPreferences(getString(R.string.preference_file_key),MODE_PRIVATE);
        //SharedPreferences.Editor editor=sharedPreferences.edit();
        //editor.clear().apply();

        //String userid=sharedPreferences.getString(getString(R.string.saved_user_id),"");

        requestQueue= Volley.newRequestQueue(this);
        String urlset=getString(R.string.url_server_base)+getString(R.string.url_users)+userid;

        JsonObjectRequest jsonObjectRequest=new JsonObjectRequest(Request.Method.GET, urlset, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject jsonObject) {

                try {
                    //JSONArray jsonArray=jsonObject.getJSONArray("settings");

                   // for (int i=0; i<jsonArray.length();i++)
                    //{
                        JSONObject settings=jsonObject.getJSONObject("settings");

                        //retrieving values from the server

                        int eventnotifmins=settings.getInt("eventNotificationMins");
                        int alldaynotiftype=settings.getInt("allDayNotificationType");
                        int alldaynotiftimehr=settings.getInt("allDayNotificationTimeHr");
                        int alldaynotiftimemin=settings.getInt("allDayNotificationTimeMin");


                        // Feeding the values of preferences from server in Shared preferences

                        sharedPreferences=PreferenceManager.getDefaultSharedPreferences(SettingsActivity.this);
                        SharedPreferences.Editor editor1=sharedPreferences.edit();
                        editor1.putString("list_preference_1",Integer.toString(eventnotifmins));
                        editor1.putString("list_preference_2",Integer.toString(alldaynotiftype));
                        editor1.putString("list_preference_3",Integer.toString(alldaynotiftimehr));
                        editor1.apply();


                        //sBindPreferenceSummaryToValueListener
                       // this.bindPreferenceSummaryToValue();


                    //}


                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {

                volleyError.printStackTrace();
                Toast.makeText(SettingsActivity.this, "Check your internet connection", Toast.LENGTH_SHORT).show();

            }
        });

        requestQueue.add(jsonObjectRequest);

    }

Thanks in advance.

Vibhor Gupta
  • 77
  • 1
  • 15
  • do you using wampserver ? – Faiz Mir Oct 08 '18 at 04:03
  • No it's a proper server. It is basically aws services from Amazon. @FaizMir – Vibhor Gupta Oct 08 '18 at 04:08
  • post your code what have you tried – Saurabh Bhandari Oct 08 '18 at 04:08
  • 3
    You have to pass header token for Authorization, Refer this answer https://stackoverflow.com/a/44049327/10449332 – deepak raj Oct 08 '18 at 04:09
  • Kindly recheck i've added my code. @SaurabhBhandari – Vibhor Gupta Oct 08 '18 at 04:10
  • 2
    @VibhorGupta follow the link deepak mentioned in comment. use your authentication token. your code is fine just add basic authentication. – Saurabh Bhandari Oct 08 '18 at 04:13
  • What is the authentication code ? Like I'm slightly confused. Can you please edit my code above so that i can understand it properly. @SaurabhBhandari – Vibhor Gupta Oct 08 '18 at 04:25
  • 401 error said that "The 401 Unauthorized error is an HTTP status code that means the page you were trying to access cannot be loaded until you first log in with a valid user ID and password. If you have just logged in and received the 401 Unauthorized error, it means that the credentials you entered were invalid for some reason." so I think there is an issue in your credentials not inside the volley. since you've mentioned that you're getting same error code 401 using postman. – Urvish rana Oct 08 '18 at 06:01

1 Answers1

1

You can add header by heading overriding getHeader() method as follows:

JsonObjectRequest jsonObjectRequest=new JsonObjectRequest(Request.Method.GET, urlset, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject jsonObject) {

                try {
                        JSONObject settings=jsonObject.getJSONObject("settings");

                        int eventnotifmins=settings.getInt("eventNotificationMins");
                        int alldaynotiftype=settings.getInt("allDayNotificationType");
                        int alldaynotiftimehr=settings.getInt("allDayNotificationTimeHr");
                        int alldaynotiftimemin=settings.getInt("allDayNotificationTimeMin");


                        // Feeding the values of preferences from server in Shared preferences

                        sharedPreferences=PreferenceManager.getDefaultSharedPreferences(SettingsActivity.this);
                        SharedPreferences.Editor editor1=sharedPreferences.edit();
                        editor1.putString("list_preference_1",Integer.toString(eventnotifmins));
                        editor1.putString("list_preference_2",Integer.toString(alldaynotiftype));
                        editor1.putString("list_preference_3",Integer.toString(alldaynotiftimehr));
                        editor1.apply();
                        //sBindPreferenceSummaryToValueListener
                       // this.bindPreferenceSummaryToValue();
                    //}

                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {

                volleyError.printStackTrace();
                Toast.makeText(SettingsActivity.this, "Check your internet connection", Toast.LENGTH_SHORT).show();

            }
        },
        {    

// This is for Authorization  Headers you can add content type as per your needs 
    @Override
    public Map<String, String> getHeaders() throws AuthFailureError {
        Map<String, String> params = new HashMap<String, String>();
        params.put("Authorization", "AWS" + " " + AWSAccessKeyId + ":" + Signature);
        return params;
    });

Here AWSAccessKeyId and Signature you can get from your AWS server. For more details of authenticating AWS services follow this link https://docs.aws.amazon.com/AmazonS3/latest/dev/RESTAuthentication.html

I hope its work for you .

Saurabh Bhandari
  • 2,438
  • 4
  • 26
  • 33