How to set HTTP header with javaagent

I’m using a Java lib which internally uses Apache HttpClient 4.3 for sending https requests. The 3rd party server requires the ‘Content-Type’ header which is unfortunately not set by the lib.

As changing the lib is not an option, I’d like to use javaagents to add the 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. Does anybody know how it could work?

Answer

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. So I was able to add the required content-type 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");
        }
    }
}