2013-03-27 50 views
0

我有一個程序,使用Jetty版本8發送一個http文章。我的響應處理程序工作,但我得到一個http響應代碼303,這是一個重定向。我閱讀了jetty 8支持這些重定向的評論,但我無法弄清楚如何設置它。我試過看javadocs,我找到了RedirectListener類,但沒有詳細說明如何使用它。我試圖猜測如何編碼它沒有工作,所以我卡住了。所有幫助表示讚賞!獲取碼頭HttpClient遵循重定向

編輯

我在碼頭的源代碼看了一下,發現當響應代碼是它只會重定向無論是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); 
    } 
} 

回答

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(); 
+0

我一直試圖讓這個工作。我是否需要實現自己的RedirectListener?當使用默認實現時,我的onResponseComplete處理程序仍然被303調用,但我從來沒有得到最終的迴應。 – jlunavtgrad 2013-03-27 16:42:48

+0

嘗試將HttpClient.setMaxRedirects(int)調整爲更高的數字。也可能是因爲你看到的重定向不符合303 +'Location:'響應頭標準(就像一些url縮寫所做的那樣) – 2013-03-27 16:50:49

+0

謝謝Joakim!我發現什麼讓我的代碼無法工作。一旦我確定你的例子運行良好。 – jlunavtgrad 2013-03-27 19:54:42