【问题标题】:Adding Header with Specified Parameter in Volley?在 Volley 中添加带有指定参数的标题?
【发布时间】:2017-08-03 05:34:04
【问题描述】:

我无法使用 Volley 库将 access_token 作为标头和 id、accessID 和 currentUser 作为参数发送。

家庭课堂

public class Home extends AppCompatActivity implements View.OnClickListener {


    LinearLayout calendar, classSchedule, progressReport, profile, fee, dshboard, setting, logout, attendance;
    android.support.v4.app.FragmentManager fragmentManager;
    public static final String Navigation_URL = "http://192.168.100.5:84/api/academics/student?id=01&accessID=4&currentUser=01";
    ImageView studentprofileimage;
    TextView profilename, sprofilename;
    String master_id, access_token, accessID;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dashboard);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        studentprofileimage = (ImageView) findViewById(R.id.avatar);//initilise student name
        profilename = (TextView) findViewById(R.id.profilename);// student profile name
        sprofilename = (TextView) findViewById(R.id.student_profilename);


        dshboard = (LinearLayout) findViewById(R.id.dashboard_layout);
        calendar = (LinearLayout) findViewById(R.id.calender_layout);
        fee = (LinearLayout) findViewById(R.id.view_fee);
        classSchedule = (LinearLayout) findViewById(R.id.class_schedule);
        progressReport = (LinearLayout) findViewById(R.id.progress_report);
        profile = (LinearLayout) findViewById(R.id.view_profile);
        setting = (LinearLayout) findViewById(R.id.mainsetting);
        logout = (LinearLayout) findViewById(R.id.mainlogout);
        attendance = (LinearLayout) findViewById(R.id.class_attendance);

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setVisibility(View.VISIBLE);

        calendar.setOnClickListener(this);
        classSchedule.setOnClickListener(this);
        fee.setOnClickListener(this);
        dshboard.setOnClickListener(this);
        progressReport.setOnClickListener(this);
        profile.setOnClickListener(this);
        setting.setOnClickListener(this);
        logout.setOnClickListener(this);
        attendance.setOnClickListener(this);
        FragmentTransaction tx = getSupportFragmentManager().beginTransaction();
        tx.replace(R.id.container, new Dashboard());
        tx.commit();

        SessionManagement session = new SessionManagement(Home.this);
        //  session.checkLogin();
        master_id = session.getMasterId();
        Log.d("TAG", "master_id:" + master_id);
        access_token = session.getAccesstToken();
        Log.d("TAG", "access token" + access_token);
        accessID = session.getAccess();
        Log.d("TAG", "access:" + accessID);
        makeJsonObjectRequest();


    }

    StudentInformation studentInformation;

    private void makeJsonObjectRequest() {

        RequestQueue requestQueue = Volley.newRequestQueue(this);
        String URL = Navigation_URL;

        StringRequest stringRequest = new StringRequest(Request.Method.GET, URL,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            studentInformation = new StudentInformation();
                            studentInformation.StdID = String.valueOf(jsonObject.get("StdID"));
                            studentInformation.Name = jsonObject.getString("NAME");
                            studentInformation.Gender = (String) jsonObject.get("GENDER");
                            studentInformation.Phonenumber = String.valueOf(jsonObject.get("PHONENO"));
                            studentInformation.StudentClass = String.valueOf(jsonObject.get("CLASS"));
                            studentInformation.Enrolled_Year = String.valueOf(jsonObject.get("ENROLLEDYEAR"));
                            studentInformation.Address = String.valueOf(jsonObject.get("ADDRESS"));
                            studentInformation.DOB = String.valueOf(jsonObject.get("DOB"));
                            studentInformation.Nationality = String.valueOf(jsonObject.get("NATIONALITY"));
                            profilename.setText(studentInformation.Name);
                            studentInformation.Photo = String.valueOf(jsonObject.get("Photo"));
                            studentInformation.CatID = String.valueOf(jsonObject.get("Cat_ID"));
                            studentInformation.base64 = String.valueOf(jsonObject.get("base64"));
                            studentInformation.Marks = String.valueOf(jsonObject.get("Marks"));


                            JSONObject studentDetails_obj = jsonObject.getJSONObject("studentDetails");
                            studentInformation.GuardianStudentId = studentDetails_obj.getString("StdID");
                            studentInformation.Guardianphonenumber = studentDetails_obj.getString("GUARDIAN_PHONE_NO");
                            studentInformation.Guardianmobilenumber = studentDetails_obj.getString("MOBILE_NO");
                            studentInformation.Guardianfirstname = studentDetails_obj.getString("First_NAME");
                            studentInformation.GuardianLastName = studentDetails_obj.getString("Last_Name");
                            studentInformation.GuardianRelation = studentDetails_obj.getString("Relation");
                            studentInformation.GuardianDOB = studentDetails_obj.getString("DOB");
                            studentInformation.GuardianEducation = studentDetails_obj.getString("Education");
                            studentInformation.GuardianOccupation = studentDetails_obj.getString("Occupation");
                            studentInformation.GuardianIncome = studentDetails_obj.getString("Income");
                            studentInformation.GuardianEmail = studentDetails_obj.getString("Email");
                            studentInformation.GuardianAddLine1 = studentDetails_obj.getString("AddLine1");
                            studentInformation.GuardianAddLine2 = studentDetails_obj.getString("AddLine2");
                            studentInformation.GuardianState = studentDetails_obj.getString("State");
                            studentInformation.GuardianCountry = studentDetails_obj.getString("Country");


                            JSONObject studentDetails_obj1 = jsonObject.getJSONObject("stdCategory");
                            studentInformation.Category = studentDetails_obj1.getString("Category");
                            studentInformation.CategoryId = studentDetails_obj1.getString("Cat_ID");


                        } catch (JSONException e) {
                            Toast.makeText(getApplicationContext(), "Fetch failed!", Toast.LENGTH_SHORT).show();
                            e.printStackTrace();
                        }

                    }

                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(Home.this, error.toString(), Toast.LENGTH_LONG).show();
            }
        }) {

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> headers = new HashMap<String, String>();
                headers.put("Authorization", "Bearer " + access_token);
                headers.put("Content-Type", "application/x-www-form-urlencoded");
                return headers;
            }
/*
            @Override
            protected Map<String, String> getParams() throws com.android.volley.AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();

                map.put("id", master_id);
                map.put("accessID", accessID);
                map.put("currentUser", master_id);
                return map;

            }    */
        };


        requestQueue.add(stringRequest);


    }


    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }


    @Override
    public void onClick(View v) {

        int id = v.getId();


        if (id == R.id.dashboard_layout) {
            fragmentManager = getSupportFragmentManager();
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            fragmentTransaction.replace(R.id.container, new Dashboard())
                    .commit();

            DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
            drawer.closeDrawer(GravityCompat.START);

        } else if (id == R.id.calender_layout) {
            fragmentManager = getSupportFragmentManager();
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            fragmentTransaction.replace(R.id.container, new CalenderFragment())
                    .commit();

            DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
            drawer.closeDrawer(GravityCompat.START);
        } else if (id == R.id.view_fee) {
            fragmentManager = getSupportFragmentManager();
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            fragmentTransaction.replace(R.id.container, new Fee())
                    .commit();

            DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
            drawer.closeDrawer(GravityCompat.START);

        } else if (id == R.id.class_schedule) {

            fragmentManager = getSupportFragmentManager();
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            fragmentTransaction.replace(R.id.container, new FragmentClassSchedule())
                    .commit();


            DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
            drawer.closeDrawer(GravityCompat.START);
        } else if (id == R.id.progress_report) {

            fragmentManager = getSupportFragmentManager();
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            fragmentTransaction.replace(R.id.container, new ProgressFragment())
                    .commit();

            DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
            drawer.closeDrawer(GravityCompat.START);
        } else if (id == R.id.class_attendance) {

            fragmentManager = getSupportFragmentManager();
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            fragmentTransaction.replace(R.id.container, new AttendanceStudentFragment())
                    .commit();

            DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
            drawer.closeDrawer(GravityCompat.START);
        } else if (id == R.id.view_profile) {

            Bundle bundle1 = new Bundle();
            bundle1.putSerializable("student_obj", studentInformation);

            Fragment fragment = new ProfileFragment();
            fragment.setArguments(bundle1);
            fragmentManager = getSupportFragmentManager();
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            fragmentTransaction.replace(R.id.container, fragment);
            fragmentTransaction.commit();

            DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
            drawer.closeDrawer(GravityCompat.START);
        } else if (id == R.id.mainsetting) {

            fragmentManager = getSupportFragmentManager();
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            fragmentTransaction.replace(R.id.container, new SettingFragment())
                    .commit();

            DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
            drawer.closeDrawer(GravityCompat.START);
        } else if (id == R.id.mainlogout) {

            SessionManagement session = new SessionManagement(Home.this);
            session.clear();
            Intent intent = new Intent(Home.this, Login.class);
            startActivity(intent);
            DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
            drawer.closeDrawer(GravityCompat.START);
        } else {
            fragmentManager = getSupportFragmentManager();
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            fragmentTransaction.replace(R.id.container, new Dashboard())
                    .commit();

            DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
            drawer.closeDrawer(GravityCompat.START);

        }


    }


}

授权:bearer如何添加到header中 部分,如图所示。

【问题讨论】:

    标签: android android-volley


    【解决方案1】:

    授权:bearer如何添加到header部分,哪个 如图所示

    使用

    headers.put("Authorization", "Bearer " + access_token);
    

    而不是

    headers.put("access_token", access_token);
    

    【讨论】:

    • 404 表示未找到,请发布您的完整 logcat 信息 + 如果您使用邮递员测试您的网络服务,请发布其屏幕截图
    • logcat ] BasicNetwork.performRequest:192.168.100.5:84/api/academics/student 的意外响应代码 404
    • 我已经发布了截图
    • 评论所有getParams 内容,然后尝试在您的应用中使用与在 Postman 中相同的完整 URL。 getParamsgetBody 不适用于 GET 请求
    • 哦,可以拼接字符串值,比如URL = Navigation_URL + "?id=" + master_id + "&amp;accessID=" + access_ID + "&amp;currentUser=" + master_id
    【解决方案2】:

    您好,使用下面的代码希望它能解决您的问题

    public void getDataFromServer(final Context context, String url, Integer method, final Map<String, String> params, final String sector ,final String AaccessToken ) {
        RequestQueue queue = Volley.newRequestQueue(context);
        StringRequest myReq = new StringRequest(Request.Method.GET, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
    
                    }
                },
                new Response.ErrorListener() {
    
                    @Override
                    public void onErrorResponse(VolleyError error) {
    
                    }
                }) {
    
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String>  params = new HashMap<String, String>();
                params.put("access_token", "your access token");
    
                return params;
            }
    
            protected Map<String, String> getParams()
                    throws com.android.volley.AuthFailureError {
                return params;
            };
    
    
        };
    
    
    
        myReq.setRetryPolicy(new DefaultRetryPolicy(15000,
                1,
                1));
        queue.add(myReq);
    }
    

    【讨论】:

    • 我不会继续 onResponse() 。它调用 onerrorResponse。
    • 可能是 url 或您的参数或您的访问令牌中存在错误,这就是您的请求出现错误块的原因
    • 我不清楚你在说什么给你的标题参数和其他参数
    • “key”是否应该与webservice KEY匹配
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-12-28
    • 1970-01-01
    • 1970-01-01
    • 2016-02-06
    • 2013-12-22
    • 2018-04-01
    • 1970-01-01
    相关资源
    最近更新 更多