2016-08-06 31 views
1

嗨,每一個它已經兩天了,現在我正在嘗試解決我的問題。 我有url鏈接,我試圖用AsyncHttpClient類調用,我需要等待鏈接所做的重定向。問題在於http get請求返回一個http響應200和http內容而不等待重定向。請問你能幫幫我嗎?
下面是代碼:
Java非常等待http重定向

private static String getAsyncRedirectedUrlFromUrl(String url) { 
    AsyncHttpClient asyncHttpClient = new DefaultAsyncHttpClient(); 
    Future<Response> response = asyncHttpClient.prepareGet(url).execute(new AsyncCompletionHandler<Response>() { 

     @Override 
     public Response onCompleted(Response response) throws Exception { 
      // Do something with the Response 
      // ... 
      response.getLocalAddress(); 
      response.getStatusCode(); 
      return response; 
     } 

     @Override 
     public void onThrowable(Throwable t) { 
      // Something wrong happened. 
     } 
    }); 
    try { 
     System.out.println("Redirection:" + response.get().getHeader("location")); 
     return response.get().getHeader("location"); 
    } catch (InterruptedException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } catch (ExecutionException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 
    return ""; 
    } 

這裏是請求鏈接:Request LINK
這裏是預期結果重定向鏈接:Expect LINK

感謝你的幫助,它會非常有幫助。

回答

0

您提供的請求鏈接確實返回一個普通的200 OK,而不是重定向。 您使用瀏覽器遇到的重定向是由javascript觸發的,它不是HTTP重定向(301等)。

AsyncHttpClient是一個HTTP客戶端,而不是瀏覽器,所以它不會執行JS。

如果你想遵循這樣的重定向,你必須解析頁面,抓取目標url,並手動發送第二個請求。

+0

感謝您的幫助:-),我已經能夠解決與Selenium的問題。 – Mehdi