在Android中使用Volley库时出现401授权错误

时间:2018-10-08 04:01:04

标签: android networking android-volley settings http-status-code-401

我正在使用Volley库来将我的SettingsActivity与服务器集成在Android Studio上。我正在执行 GET方法的请求,以便从服务器检索值。但是,当我尝试做同样的事情时,出现了凌空错误,提示401错误

也在POSTMAN应用程序上测试了自己的网址。它显示了相同的401授权错误

问题1:在Android平台的Volley库中出现此类错误的原因是什么?

问题2:如何解决该问题,以便可以在Android平台上执行Volley请求。

参考代码:

@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);

    }

谢谢。

1 个答案:

答案 0 :(得分:0)

您可以通过按如下方式覆盖getHeader()方法来添加标头:

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;
    });

您可以从 AWS 服务器获取AWSAccessKeyId和签名。 有关对 AWS 服务进行身份验证的详细信息,请点击以下链接https://docs.aws.amazon.com/AmazonS3/latest/dev/RESTAuthentication.html

希望它对您有用。