Android Volley read and store HTTP Header

2019-07-25 05:20发布

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

1条回答
闹够了就滚
2楼-- · 2019-07-25 05:53

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

public final class TokenHandler {
    private TokenHandler() {}

    private static String token = "";

    public static void setToken(String newToken) {
        if (newToken != null)
            token = newToken;
    }

    public static String getToken() {
        return token;
    }
}

And you set it up on your sub-classed Request like this:

AuthRequest.java

public class AuthRequest extends JsonObjectRequest{

    // constructor

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

            // set token after receiving from login response
            TokenHandler.setToken(response.headers.get("x-auth"));

            return Response.success(jsonResponse, HttpHeaderParser.parseCacheHeaders(response));
        } catch (UnsupportedEncodingException | JSONException e) {
            return Response.error(new ParseError(e));
        }
    }

    @Override
    public Map<String, String> getHeaders() throws AuthFailureError {
        Map<String, String> headers = new HashMap<>();
        headers.put("x-auth", TokenHandler.getToken());
        return headers;
    }
}
查看更多
登录 后发表回答