Search code examples
jettyjetty-8

Get Jetty HttpClient to follow redirects


I've got a program that uses Jetty version 8 to send an http post. My response handler works, but I'm getting an http response code 303, which is a redirect. I read a comment that jetty 8 has support for following these redirects, but I can not figure out how to set it up. I've tried looking at the javadocs, and I found the RedirectListener class, but no details on how to use it. My attempts at guessing how to code it haven't worked so I'm stuck. All help is appreciated!

Edit

I looked through the jetty source code and found that it will only redirect when the response code is either 301 or 302. I was able to override the RedirectListener to get it to handle repose code 303 as well. After that Joakim's code works perfectly.

public class MyRedirectListener extends RedirectListener
{
   public MyRedirectListener(HttpDestination destination, HttpExchange ex)
   {
      super(destination, ex);
   }

   @Override
   public void onResponseStatus(Buffer version, int status, Buffer reason)
       throws IOException
   {
      // Since the default RedirectListener only cares about http
      // response codes 301 and 302, we override this method and
      // trick the super class into handling this case for us.
      if (status == HttpStatus.SEE_OTHER_303)
         status = HttpStatus.MOVED_TEMPORARILY_302;

      super.onResponseStatus(version,status,reason);
   }
}

Solution

  • Simple enough

    HttpClient client = new HttpClient();
    client.registerListener(RedirectListener.class.getName());
    client.start();
    
    // do your exchange here
    ContentExchange get = new ContentExchange();
    get.setMethod(HttpMethods.GET);
    get.setURL(requestURL);
    
    client.send(get);
    int state = get.waitForDone();
    int status = get.getResponseStatus();
    if(status != HttpStatus.OK_200)
       throw new RuntimeException("Failed to get content: " + status);
    String content = get.getResponseContent();
    
    // do something with the content
    
    client.stop();