Skip to content

Extending With Java

Chris Heald edited this page Mar 18, 2015 · 3 revisions

Since Manticore is built on the Apache HTTP Commons components, you can leverage their power to handle unusual needs when making requests. For example, if you wanted to keep a log of all redirects that Manticore makes per request, you can use it by assigning a RedirectStratgy to your client during instantiation.

First, we'll build our redirect strategy:

class LoggingRedirectStrategy
  java_import "org.apache.http.client.methods.HttpGet"

  # This is equivalent to creating a class that implements this Java interface.
  # RedirectStrategy requires two methods: getRedirect and isRedirected. Here we'll implement them
  include org.apache.http.client::RedirectStrategy

  def getRedirect(request, response, context)
    # We're operating on Java objects here, so we'll go ahead and use the appropriate API.
    # Don't confuse these for Manticore request/response objects!
    location_header = response.get_first_header("location").get_value

    # The Context is an arbitrary key-value store associated with each request. We can shove a
    # Ruby array into it. Handy!
    redirects = context.get_attribute("redirects")
    if redirects.nil?
      redirects = []
      context.set_attribute("redirects", redirects)
    end

    # Since we're redirecting, we'll go ahead and add an entry to our redirects log...
    redirects << [response.get_status_line.get_status_code, location_header]

    # ...then return a new HttpGet representing the next request in the chain.
    HttpGet.new(location_header)
  end

  # Very simple - we'll only redirect on Location headers.
  def isRedirected(request, response, context)
    !response.get_first_header("location").nil?
  end
end

Now, we just instantiate Manticore with that strategy:

client = Manticore::Client.new(cookies: true) do |builder, request_config|
  builder.set_redirect_strategy LoggingRedirectStrategy.new
end

Then, we can make a request:

response = client.get "http://google.com"
p response.context.get_attribute("redirects") # => [[301, "https://www.google.com"]]
Clone this wiki locally