Skip to content

3. How to implement interceptors those can intercept requests and responses

Tamás Kőhegyi edited this page Jun 3, 2021 · 4 revisions

The interfaces

Interface to intercept requests:

package website.magyar.mitm.proxy;

import website.magyar.mitm.proxy.http.MitmJavaProxyHttpRequest;

public interface RequestInterceptor {
    void process(MitmJavaProxyHttpRequest request);
}

Interface to intercept responses:

package website.magyar.mitm.proxy;

import website.magyar.mitm.proxy.http.MitmJavaProxyHttpResponse;

public interface ResponseInterceptor {
    void process(MitmJavaProxyHttpResponse response);
}

Example Request Interceptor

This example request interceptor do not manipulate the request, just counts it. The counter can be read and reset to zero.

package website.magyar.mitm.proxy.help;

import website.magyar.mitm.proxy.RequestInterceptor;
import website.magyar.mitm.proxy.http.MitmJavaProxyHttpRequest;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Class that is able to intercept and process every request going through the proxy, by implementing the RequestInterceptor interface.
 * It counts every request that is intercepted.
 */
public class DummyRequestInterceptor implements RequestInterceptor {

    private AtomicInteger requestCount;

    public DummyRequestInterceptor(AtomicInteger requestCount) {
        this.requestCount = requestCount;
    }

    public void process(final MitmJavaProxyHttpRequest request) {
        requestCount.incrementAndGet();
    }

    public void resetRequestCount() {
        requestCount.set(0);
    }

    public int getRequestCount() {
        return requestCount.get();
    }
}

Now you are ready to manipulate the requests.