我正在编写一个-javaagent
以使用Java的Instrumentation API(例如javassist
/ asm
)捕获HTTP请求和响应。我可以在方法周围插入代码,但是如何捕获方法是否要进行HTTP调用并捕获HTTP请求详细信息,响应代码?
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;
});
}