mercredi 13 octobre 2021

MessageHeader field (requests) from HttpURLConnection via Reflection

Because i need to write a unit test for an existing library, i am trying to work around the limitation (as explained here) that you cannot retrieve an already set "authorization" header, using reflection.

The code i'm using is very typical code as i've used it similarily dozens of times to access private fields:

HttpURLConnection conn = (HttpURLConnection) new URL("https://stackoverflow.com").openConnection();
conn.setRequestProperty("Authorization", "Basic Zm9vYmFyOnNlY3JldA==");
try {
    Field requests = conn.getClass().getSuperclass().getSuperclass().getSuperclass().getDeclaredField("requests");
    requests.setAccessible(true);
    MessageHeader headers = (MessageHeader) requests.get(conn); // Problem: returns null
    return headers.getValue(headers.getKey("Authorization"));
} catch (IllegalAccessException | NoSuchFieldException e) {
    e.printStackTrace();
}

However – extraction via Field::get (see commented line) fails and null is returned.

Looking at the base class of HttpUrlConnection, which is URLConnection i know i'm looking for the requests field. Debugging through it, i can see the field i want to extract (even showing the "Authorization" values):

Debug watch

In the line of code that fails to return the MessageHeader object, it looks like i have a reference to the field in URLConnection:

Debug watch

But i must be missing something here – can anybody tell, what?





Aucun commentaire:

Enregistrer un commentaire