How can I capture the HTTP request and response using Instrumentation's Java API?

664 Views Asked by At

I am writing a -javaagent to capture the HTTP request and response using Java's Instrumentation API such as javassist/ asm. I could insert the code around the method but how can I capture if the method is about to make a HTTP call and capture the HTTP request details, response code?

public static void premain(
    String agentArgs,
    Instrumentation inst
) throws IOException {

    inst.addTransformer((classLoader, className, classBeingRedefined, protectionDomain, classfileBuffer) -> {

        try {
            ClassPool cp = ClassPool.getDefault();

            CtClass cc = cp.get("other.Stuff");
            CtMethod m = cc.getDeclaredMethod("run");
            m.addLocalVariable("elapsedTime", CtClass.longType);
            m.insertBefore("elapsedTime = System.currentTimeMillis();");
            m.insertAfter(
            "{elapsedTime = System.currentTimeMillis() - elapsedTime;"
                        + "System.out.println(\"Method Executed in ms: \" + elapsedTime);}");
            byte[] byteCode = cc.toBytecode();
            cc.detach();
            return byteCode;
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        return null;
    });
}
0

There are 0 best solutions below