I have a node backend, which returns the id, email and JWT token
of an user after login. Id and email are set in the JSON response body and the token is set as a HTTP header.
What I want to do is just read that token from the header and store it for future requests until the user logs out, since I am deleting the token afterwards.
I found several posts about how to set the header by overriding getHeaders()
and how to read the header by overriding parseNetworkResponse()
. My problem with parseNetworkResponse()
is, that I would have to write the information on the JSON body, which I want to avoid. My other problem with getHeaders()
is that I can't "hardcode" my header into the HashMap, because I have to use the JWT token
generated from the server.
This is my first Android project and overall I believe it's a simple use case but I am confused a bit at this point, so any help would be much appreciated.
Relevant Code:
// AuthenticationRequest.java
public class AuthenticationRequest extends JsonObjectRequest{
public AuthenticationRequest(int method, String url, JSONObject payload,
Response.Listener<JSONObject> listener, Response.ErrorListener errorListener) {
super(method, url, payload, listener, errorListener);
}
@Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
try {
String jsonString = new String(response.data, HttpHeaderParser.parseCharset(response.headers, PROTOCOL_CHARSET));
JSONObject jsonResponse = new JSONObject(jsonString);
// I could fetch here with response.headers
return Response.success(jsonResponse, HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException | JSONException e) {
return Response.error(new ParseError(e));
}
}
}
// BasicActivity.java
private void sendRequestToServer(String url, int method, JSONObject payload, final Class toGo) {
final AuthenticationRequest request =
new AuthenticationRequest(method, url, payload, response -> {
try {
startActivity(new Intent(this, toGo).putExtra("jsonData", response.toString()));
} catch (Exception e) {
e.printStackTrace();
}
}, Throwable::printStackTrace);
VolleySingleton.getInstance(this).addToRequestQueue(request);
}
So after playing around a bit I solved my issue. I created a
TokenHandler
class which is really basic and just cares about setting/getting and later deleting a token.TokenHandler.java
And you set it up on your sub-classed Request like this:
AuthRequest.java