简体   繁体   English

如何使用 javaagent 设置 HTTP header

[英]How to set HTTP header with javaagent

I'm using a Java lib which internally uses Apache HttpClient 4.3 for sending https requests.我正在使用 Java 库,它在内部使用 Apache HttpClient 4.3 来发送 https 请求。 The 3rd party server requires the 'Content-Type' header which is unfortunately not set by the lib.第 3 方服务器需要 'Content-Type' header 不幸的是,lib 没有设置它。

As changing the lib is not an option, I'd like to use javaagents to add the header.由于更改库不是一种选择,我想使用 javaagents 添加 header。

I found this useful tutorial which made me believe it's possible to achieve this:https://httptoolkit.tech/blog/how-to-intercept-debug-java-http/ But I couldn't figure out which interface of HttpClient 4.3 to manipulate to set the header.我发现这个有用的教程让我相信可以实现这一点:https://httptoolkit.tech/blog/how-to-intercept-debug-java-http/但我无法弄清楚 HttpClient 4.3 的哪个接口操作设置 header。 Does anybody know how it could work?有人知道它是如何工作的吗?

The solution I came up with: using bytebuddy to intercept the 'doExecute' Method of the Apache InternalHttpClient that is used by the 3rd party library.我想出的解决方案:使用 bytebuddy 拦截第 3 方库使用的 Apache InternalHttpClient的“doExecute”方法。 So I was able to add the required content-type header.所以我能够添加所需的内容类型 header。

public class AgentMain {

    public static void premain(String agentArgs, Instrumentation inst) {
        new AgentBuilder.Default()
                .type(named("org.apache.http.impl.client.InternalHttpClient"))
                .transform((builder, type, classLoader, module) ->
                        builder.method(named("doExecute"))
                                .intercept(Advice.to(HttpClientAdvice.class))
                ).installOn(inst);
    }

    public static void agentmain(String agentArgs, Instrumentation inst) {
        // Not used
    }

    public static class HttpClientAdvice {
        @Advice.OnMethodEnter
        public static void doExecute(@Advice.AllArguments Object[] args) {
            final HttpRequest request = (HttpRequest) args[1];
            request.addHeader("Content-Type", "text/xml");
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM