[英]Adding JWT Token in Volley Request
I am using Node.js at the Backend, and need to send some params(parameters) and a jwt token(for authorization) in header of a GET request. 我在后端使用Node.js,并且需要在GET请求的标头中发送一些参数(参数)和jwt令牌(用于授权)。 I am using express-jwt module at the node server. 我在节点服务器上使用express-jwt模块。 The request need to be authorized using jwt token there. 该请求需要在那里使用jwt令牌进行授权。 Simply sending the token as params do not work there. 只是将令牌作为参数发送并不在那里。
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);
}
` `
Just override the Request's method getHeaders() 只需重写请求的方法getHeaders()
Here's an example : 这是一个例子:
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("Authorization", "Bearer "+ yourToken);
return params;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.