javalittle-proxy

How to make LittleProxy to cut off the half of the HTTP response's body?


I have the LittleProxy sample, that is used for replacing the response's HTTP headers when it is intercepted and sent back:

package com.example.proxy;

in pom.xml we have the dependency:

    <dependency>
        <groupId>org.littleshoot</groupId>
        <artifactId>littleproxy</artifactId>
        <version>1.1.2</version>
    </dependency>

and then the classes. The main class:

import org.littleshoot.proxy.HttpProxyServer;
import org.littleshoot.proxy.HttpProxyServerBootstrap;
import org.littleshoot.proxy.extras.SelfSignedMitmManager;
import org.littleshoot.proxy.impl.DefaultHttpProxyServer;

public class LittleProxyExample {

    public static void main(String[] args) {
        // Настраиваем и запускаем прокси-сервер
        HttpProxyServer proxyServer = org.littleshoot.proxy.impl.DefaultHttpProxyServer.bootstrap()
                .withPort(8081) // Указываем порт, на котором будет работать прокси
                .withManInTheMiddle(new SelfSignedMitmManager()) // Добавляем обработчик запросов
                .withFiltersSource(new RequestInterceptor())
                .start();

        System.out.println("Proxy server started on port 8081");
    }
}

And the interceptor:

package com.example.proxy;

import io.netty.buffer.CompositeByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.handler.codec.DecoderResult;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;
import org.littleshoot.proxy.HttpFiltersAdapter;
import org.littleshoot.proxy.HttpFiltersSourceAdapter;

import java.nio.charset.StandardCharsets;

public class RequestInterceptor extends HttpFiltersSourceAdapter {

    @Override
    public HttpFiltersAdapter filterRequest(HttpRequest originalRequest) {
        return new HttpFiltersAdapter(originalRequest) {

            @Override
            public HttpResponse clientToProxyRequest(HttpObject httpObject) {
                if (httpObject instanceof HttpRequest) {
                    HttpRequest request = (HttpRequest) httpObject;

                    // replace the header
                    request.headers().set("User-Agent", "LittleProxy/Example");

                    // logging the query
                    System.out.println("Modified Request: " + request.uri());
                }
                return null; // going ahead
            }

            @Override
            public HttpObject serverToProxyResponse(HttpObject httpObject) {
                // updating headers of the response here

                HttpResponse response = (HttpResponse) httpObject;
                response.headers().set("Test", "Test");

                return super.serverToProxyResponse(response);
            }
        };
    }

    @Override
    public int getMaximumRequestBufferSizeInBytes() {
        return 10 * 1024 * 1024; 
    }

    @Override
    public int getMaximumResponseBufferSizeInBytes() {
        return 10 * 1024 * 1024; 
    }
}

So I'd like to cut the second half of the response data off (to test some client in order will it crash on the response with the broken structure). Also I'd like to apply this cut only for the specific URI of the reuest from the client to the server. And HttpResponse object doesn't have any API for that.

How can I get it?


Solution

  • FullHttpResponse is needed to manipulate the body of the http response.

    @Override
            public HttpObject serverToProxyResponse(HttpObject httpObject) {
                
                HttpResponse response = (HttpResponse) httpObject;
                response.headers().set("Test", "Test");
    
    
                if (httpObject instanceof FullHttpResponse) {
                    System.out.println("FullHttpResponse ----------------------------------------");
                    FullHttpResponse fullHttpResponse = (FullHttpResponse) response;
                    
    //I'd like to do if for very specific request and tha't how I can filter for its URL
    if (originalRequest.uri().toString().contains("search")) {
                            String responseBody = fullHttpResponse.content().toString(StandardCharsets.UTF_8);
                        try {
                            Thread.sleep(200);
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                        response.setStatus(HttpResponseStatus.BAD_GATEWAY);
                        int newLength = responseBody.length() / 2;
                        String truncatedBody = responseBody.substring(0, newLength);
    
                        //here we replace the response with the reduced body
                        fullHttpResponse.content().clear().writeBytes(Unpooled.copiedBuffer(truncatedBody, StandardCharsets.UTF_8));
                    }
    
                }
    
                return super.serverToProxyResponse(response);
            }
        };
    }