最近使用一个第三方的SDK来请求数据,但是请求的服务器对ip有白名单限制,SDK使用的apache的commons-httpclient: 3.1

发送请求。于是尝试使用ApectJ运行时织入,拦截发送HTTP请求的代码,修改参数.

依赖(用的1.9.19版本)

        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjrt</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
        </dependency>

maven插件

<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>aspectj-maven-plugin</artifactId>
    <executions>
        <execution>
            <goals>
                <goal>compile</goal>
            </goals>
        </execution>
    </executions>
</plugin>

切面

import org.apache.commons.httpclient.HttpMethod;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class HttpClientAspect {

    public static HttpClientAspect aspectOf() {
        return new HttpClientAspect();
    }

    @Around("execution(* org.apache.commons.httpclient.HttpClient.executeMethod(..))")
    public Object aroundHttpExecution(ProceedingJoinPoint joinPoint) throws Throwable {
        System.out.println("======================================");
        Object[] args = joinPoint.getArgs();

        // 获取HttpMethod参数
        if (args != null && args.length > 0 && args[0] instanceof HttpMethod) {
            HttpMethod httpMethod = (HttpMethod) args[0];

            // 添加自定义请求头
            httpMethod.addRequestHeader("**********", "**********");
            // 添加其他需要的请求头
        }

        // 继续执行原方法
        return joinPoint.proceed();
    }

}

aop配置(resource:META-INF/aop.xml)

<!DOCTYPE aspectj PUBLIC "-//AspectJ//DTD//EN" "https://www.eclipse.org/aspectj/dtd/aspectj.dtd">
<aspectj>
    <weaver options="-verbose -showWeaveInfo">
        <include within="org.apache.commons.httpclient.*"/>
    </weaver>
    <aspects>
        <!-- 指定切面类 -->
        <aspect name="com.****.aspect.HttpClientAspect"/>
    </aspects>
</aspectj>

运行时参数

-javaagent:"C:\Users\***\aspectjweaver-1.9.19.jar" --add-opens java.base/java.lang=ALL-UNNAMED