0

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);
   }
}
jlunavtgrad
  • 997
  • 1
  • 11
  • 21

1 Answers1

1

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();
Joakim Erdfelt
  • 46,896
  • 7
  • 86
  • 136
  • I've been trying to get this working. Do I need to implement my own RedirectListener? When use the default implementation my onResponseComplete handler still gets called with a 303, but I never get the final response. – jlunavtgrad Mar 27 '13 at 16:42
  • Try adjusting the HttpClient.setMaxRedirects(int) to a higher number. It could also be that the redirect you are seeing isn't conforming to the 303 + `Location:` response header standard (like some url shorteners do) – Joakim Erdfelt Mar 27 '13 at 16:50
  • Thank you Joakim! I found out what was keeping my code from working. Once I fixed that your example worked great. – jlunavtgrad Mar 27 '13 at 19:54