我有一个使用Jetty版本8发送http帖子的程序。我的响应处理程序工作,但我得到一个http响应代码303,这是一个重定向。我读到了一条评论,即jetty 8支持跟踪这些重定向,但我无法弄清楚如何设置它。我已经尝试查看javadocs,我找到了RedirectListener类,但没有详细说明如何使用它。我试图猜测如何编码它没有奏效,所以我被困住了。感谢所有帮助!
修改
我浏览了一下jetty源代码,发现它只会在响应代码为301或302时重定向。我能够覆盖RedirectListener以使其处理休止代码303。之后,Joakim的代码完美无缺。
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);
}
}
答案 0 :(得分:1)
足够简单
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();