ASM字节码与HttpURLConnection

时间:2013-02-25 05:32:32

标签: java-bytecode-asm bytecode-manipulation

使用ASM ByteCode库,在创建HttpUrlConnection ic时添加请求标头(UUID) 下面是我的代码 - 我也得到输出===>这是Http CONNECT方法!但不知道如何添加标题?

    package com.eg.agent;

    import org.objectweb.asm.MethodVisitor;
    import org.objectweb.asm.Opcodes;

    public class EgHttpMethodVisitorAdapter extends MethodVisitor {

        private String methodName;
        private String className;
        private String description;

        public EgHttpMethodVisitorAdapter(MethodVisitor mv , String  methodName , String description , String className) {
            super(Opcodes.ASM4, mv);
            this.methodName = methodName;
            this.className = className;
            this.description = description;
        }

        public void visitCode() {
            super.visitCode();
            System.out.println("\t [HTTP URL CONNECTION - Method Name]"+methodName +"  Class NAME: "+className  + "  DESC :"+description);
            boolean isConnect =  false;
            if(methodName.equals("connect") && description.equals("()V"))
                isConnect = true;
            if(isConnect) {
                mv.visitFieldInsn(Opcodes.GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;");
                mv.visitLdcInsn (" ====> This is Http CONNECT Method!");
                mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/io/PrintStream","println", "(Ljava/lang/String;)V");
            }
        }

        public void visitMaxs(int maxStack, int maxLocals) {
            super.visitMaxs(maxStack + 4, maxLocals);
        }
    }

2 个答案:

答案 0 :(得分:1)

我已经解决了..附上了visitCode方法。

    public void visitCode() {
        super.visitCode();
        boolean isConnect =  false;
        if(methodName.equals("connect") && description.equals("()V"))
            isConnect = true;

        if(isConnect) {
            // Dynamically add UUID .. 
            mv.visitMethodInsn(Opcodes.INVOKESTATIC, "java/util/UUID", "randomUUID", "()Ljava/util/UUID;");
            mv.visitVarInsn(Opcodes.ASTORE, 3); 
            mv.visitVarInsn(Opcodes.ALOAD, 0);  
            mv.visitLdcInsn("GUID");
            mv.visitVarInsn(Opcodes.ALOAD, 3); 
            mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/util/UUID", "toString", "()Ljava/lang/String;");
            mv.visitMethodInsn(Opcodes.INVOKEVIRTUAL, "java/net/HttpURLConnection", "addRequestProperty", "(Ljava/lang/String;Ljava/lang/String;)V");
            mv.visitCode();
        }
    }

答案 1 :(得分:0)

您可能会发现ASM FAQ Question 11有帮助。