在 Volley 请求中添加 JWT 令牌

Adding JWT Token in Volley Request

我在后端使用 Node.js,需要在 GET 请求的 header 中发送一些参数(参数)和一个 jwt 令牌(用于授权)。 我在节点服务器上使用 express-jwt 模块。该请求需要在那里使用 jwt 令牌进行授权。简单地将令牌作为参数发送在那里不起作用。

    private void getInfo(final String instanceId, final String token) {
//token is jwt token
            StringRequest strReq = new StringRequest(Request.Method.GET,
                    Config.URL_GET_ID_INFO, new Response.Listener<String>() {

                @Override
                public void onResponse(String response) {
                    Log.d(TAG, response);

                    try {
                        JSONObject responseObj = new JSONObject(response);
                        boolean error = responseObj.getBoolean("error");
                        String message = responseObj.getString("message");
                        if (!error) {

                            Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();

                        } else {
                            Toast.makeText(getApplicationContext(),
                                    "Error: " + message,
                                    Toast.LENGTH_LONG).show();
                        }

                        // hiding the progress bar
                        //progressBar.setVisibility(View.GONE);

                    } catch (JSONException e) {
                        Toast.makeText(getApplicationContext(),
                                "Error: " + e.getMessage(),
                                Toast.LENGTH_LONG).show();

                       // progressBar.setVisibility(View.GONE);
                    }

                }
            }, new Response.ErrorListener() {

                @Override
                public void onErrorResponse(VolleyError error) {
                    Log.e(TAG, "Error: " + error.getMessage());
                    Toast.makeText(getApplicationContext(),
                            error.getMessage(), Toast.LENGTH_SHORT).show();
                    //progressBar.setVisibility(View.GONE);
                }
            }) {
                @Override
                protected Map<String, String> getParams() {
                    Map<String, String> params = new HashMap<String , String>();
                    params.put("instanceId", instanceId);

                    //Need to send jwt along with params, but do not know how to include it in the request.
                    Log.e(TAG, "Posting params: " + params.toString());

                    return params;
                }



            };

            // Adding request to request queue
            MyApplication.getInstance().addToRequestQueue(strReq);
        }

`

只需覆盖 Request 的方法 getHeaders()

这是一个例子:

@Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            Map<String, String> params = new HashMap<String, String>();
            params.put("Authorization", "Bearer "+ yourToken);
            return params;
        }