2015-03-31 24 views
4

我有以下代碼將通過HttpUrlConnection調用服務器。HttpUrlConnection重定向到其他servlet沒有發生

String response = HttpUtil.submitRequest(json.toJSONString(), "http://ipaddr:port/SessionMgr/validateSession?sessionId=_78998348uthjae3a&showLoginPage=true"); 

上述線將調用以下代碼:

public static String submitRequest(String request, String **requestUrl**) { 
    try { 
     URL url = new URL(requestUrl); 
     HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 
     conn.setDoOutput(true); 
     conn.setRequestMethod("POST"); 
     conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8"); 
     OutputStream os = conn.getOutputStream(); 
     os.write(request.getBytes()); 
     os.flush(); 
     if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) { 
      throw new RuntimeException("Failed : HTTP error code : " 
        + conn.getResponseCode()); 
     } 

     BufferedReader br = new BufferedReader(new InputStreamReader(
       (conn.getInputStream()))); 
     String output; 
     StringBuffer sb = new StringBuffer(); 
     while ((output = br.readLine()) != null) { 
      sb.append(output); 
     } 
     conn.disconnect(); 
     return sb.toString(); 

    } catch (MalformedURLException e) { 
    } catch (IOException e) { 
    } 
    return ""; 
} 

requestUrl將去下面的servlet:

public class ValidateSessionServlet extends HttpServlet { 
    String session = req.getParameter(sessionId); 
    if (session == null) { 
    // redirect to servlet which will display login page. 
    response.setContentType("text/html"); 
      String actionUrl = getIpPortUrl(request) 
          + PropertyConfig.getInstance().getFromIdPConfig(globalStrings.getCheckSSOSession()); 
      out.write("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\"> \n"); 
      out.write("<html><head><body onload=\"document.forms[0].submit()\">\n"); 
      out.write("<form method=\"POST\" action=\"" + actionUrl + "\">\n"); 
      out.write("<input type=\"hidden\" name=\"locale\" value=\"" + locale + "\"/>\n"); 
      out.write("<input type=\"hidden\" name=\"Sessionrequest\" value=\"" + true + "\"/>\n"); 
      out.write("</form>\n</body>\n</html>\n"); 
    } 
} 

在上面的代碼的形式應到的servlet如actionUrl中所提到的,但它又一次轉到步驟(1)中的servlet。

1)我可否知道我們可以在步驟(3)中將上述html表單提交併重定向到actionUrl中的servlet。

根據上述代碼,我總結了這個要求。如果會話爲空,我必須將用戶重定向到登錄頁面並針對數據庫進行驗證,然後響應應轉到步驟(1),是否有可能?

+0

有些身體請告訴我它是否有解決方案? – 2015-04-01 04:36:17

+0

你執行一個服務器端文章,你如何處理POST的輸出?順便說一句,我認爲你正在採取一種危險的方式。如果你想在HTTP上調用類似RPC的調用,那麼你應該依賴JSON響應,混合模式(JSON或HTML)容易出錯(可以完成,但會觸發各種問題)。 – BigMike 2015-04-02 07:31:24

+0

您是否在進行各種自動化操作的網站,自動登錄等?如果是這樣,請考慮使用硒。 – 2015-04-02 07:58:48

回答

3

如果你希望你的HttpUrlConnection支持重定向,你需要設置你的HttpUrlConnection這樣的:

... 
conn.setRequestProperty("User-agent", "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/13.0.782.215 Safari/535.1"); 
conn.setInstanceFollowRedirects(true); 
... 

然後,如果你的服務器重定向您的要求在其他地方,conn將接收器重定向的響應。

2

爲了澄清,setInstanceFollowRedirects(true)僅指示HTTP重定向是否應該自動跟隨HttpURLConnection實例。在你的特定情況下,似乎你想根據session是否爲null(或基於特定應用程序邏輯的其他條件)重定向到servlet。

正確的(和更多的防蟲解決方案)是檢查HTTP 3xx狀態代碼的情況下,並手動處理重定向。下面的代碼片段爲例:

if (responseStatusCode != HttpURLConnection.HTTP_OK) { 
    switch(responseStatusCode){ 
     case HttpURLConnection.HTTP_MOVED_TEMP: 
      // handle 302 
     case HttpURLConnection.HTTP_MOVED_PERM: 
      // handle 301 
     case HttpURLConnection.HTTP_SEE_OTHER:       
      String newUrl = conn.getHeaderField("Location"); // use redirect url from "Location" header field 
      String cookies = conn.getHeaderField("Set-Cookie");  // if cookies are needed (i.e. for login) 
      // manually redirect using a new connection 
      conn = (HttpURLConnection) new URL(newUrl).openConnection(); 
      conn.setRequestProperty("Cookie", cookies); 
      conn.addRequestProperty("User-agent", "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/13.0.782.215 Safari/535.1"); 
     default: 
      // handle default (other) case 
    } 
} 

上面的代碼相似,我用我的應用程序的用戶登錄重定向,而我發現,這是很容易調試。 (一般來說,我手動處理HTTP狀態代碼的情況下,以避免錯誤的道路。)

最後,我會建議使用一個良好的JSON庫,如json.org,來解析您的迴應。