Search code examples
javaproxylittle-proxy

Setting remote ip and port in littleproxy


In littleProxy, how can I set the remote ip and port? The sample in their website :

HttpProxyServer server =
    DefaultHttpProxyServer.bootstrap()
        .withPort(8080)
        .start();

only sets the local port.


Solution

  • The request target must be in absolute-form, as specified by RFC 7230, section 5.3.2, to be forwarded by LittleProxy. The following code works in LittleProxy v1.1.0beta1:

    Pattern REQUEST_TARGET_ORIGIN_FORM_PREFIX = Pattern.compile("/[^/]");
    
    @Override
    public HttpResponse clientToProxyRequest(HttpObject httpObject) {
      if (httpObject instanceof HttpRequest) {
        HttpRequest httpRequest = (HttpRequest) httpObject;
        if (REQUEST_TARGET_ORIGIN_FORM_PREFIX.matcher(httpRequest.getUri()).lookingAt()) {
          String uriRemote = "http://myRemoteHost:myRemotePort" + httpRequest.getUri();
          httpRequest.setUri(uriRemote);
        }
      }
      return null;
    }